-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleetcode1559.cpp
More file actions
50 lines (40 loc) · 1.15 KB
/
leetcode1559.cpp
File metadata and controls
50 lines (40 loc) · 1.15 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
class Solution {
public:
int m, n;
vector<vector<int>> vis;
int dx[4] = {1, -1, 0, 0};
int dy[4] = {0, 0, 1, -1};
bool dfs(int r, int c, int pr, int pc, vector<vector<char>>& grid) {
vis[r][c] = 1;
for (int k = 0; k < 4; k++) {
int nr = r + dx[k];
int nc = c + dy[k];
if (nr < 0 || nc < 0 || nr >= m || nc >= n) continue;
if (grid[nr][nc] != grid[r][c]) continue;
if (!vis[nr][nc]) {
if (dfs(nr, nc, r, c, grid)) return true;
}
else {
if (nr != pr || nc != pc) {
return true;
}
}
}
return false;
}
bool containsCycle(vector<vector<char>>& grid) {
m = grid.size();
n = grid[0].size();
vis.assign(m, vector<int>(n, 0));
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (!vis[i][j]) {
if (dfs(i, j, -1, -1, grid)) {
return true;
}
}
}
}
return false;
}
};