-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path1559_Detect_Cycles_in_2D_Grid.cpp
More file actions
55 lines (50 loc) 路 2.33 KB
/
Copy path1559_Detect_Cycles_in_2D_Grid.cpp
File metadata and controls
55 lines (50 loc) 路 2.33 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/*
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.
Example 1:
Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]]
Output: true
Explanation: There are two valid cycles shown in different colors in the image below:
Example 2:
Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]]
Output: true
Explanation: There is only one valid cycle highlighted in the image below:
Example 3:
Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]]
Output: false
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 500
grid consists only of lowercase English letters.
*/
class Solution {
static constexpr int dirs[4][2] = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
public:
bool containsCycle(vector<vector<char>>& grid) {
int m = grid.size();
int n = grid[0].size();
bitset<250005> visit;
auto dfs = [&](this auto&& dfs, int r, int c, int pr, int pc) -> bool {
visit[r * n + c] = 1;
for (const auto& d : dirs) {
int nr = r + d[0];
int nc = c + d[1];
if (nr != pr || nc != pc)// skip parent
if (nr >= 0 && nr < m && nc >= 0 && nc < n) // check if in bounds
if (grid[nr][nc] == grid[r][c]) // same char -> follow path
if (visit[nr * n + nc] || dfs(nr, nc, r, c))
return true;
}
return false;
};
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
if (!visit[i * n + j] && dfs(i, j, -1, -1))
return true;
return false;
}
};