[LeetCode] Detect Cycles in 2D Grid

1559. Detect Cycles in 2D Grid

Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid.

A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell.

Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell.

Return true if any cycle of the same value exists in grid, otherwise, return false.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Solution {
bool bfs(vector<vector<char>>& g, vector<vector<bool>>& vis, int sy, int sx) {
int n = g.size(), m = g[0].size();
int dy[4]{-1,0,1,0}, dx[4]{0,1,0,-1};
queue<pair<int, int>> q;
q.push({sy, sx});
vis[sy][sx] = true;

while(!q.empty()) {
auto [y, x] = q.front(); q.pop();
int count = 0;
for(int i = 0; i < 4; i++) {
int ny = y + dy[i], nx = x + dx[i];
if(0 <= ny and ny < n and 0 <= nx and nx < m and g[ny][nx] == g[y][x]) {
if(vis[ny][nx]) count++;
else {
vis[ny][nx] = true;
q.push({ny,nx});
}
}
if(count >= 2) return true;
}
}

return false;
}
public:
bool containsCycle(vector<vector<char>>& grid) {
int n = grid.size(), m = grid[0].size();
vector<vector<bool>> vis(n, vector<bool>(m));
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(vis[i][j]) continue;
if(bfs(grid,vis,i,j)) return true;
}
}
return false;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/05/PS/LeetCode/detect-cycles-in-2d-grid/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.