forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.js
33 lines (33 loc) · 1.15 KB
/
Solution.js
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
/**
* @param {character[][]} grid
* @return {boolean}
*/
var containsCycle = function (grid) {
const [m, n] = [grid.length, grid[0].length];
const vis = Array.from({ length: m }, () => Array(n).fill(false));
const dirs = [-1, 0, 1, 0, -1];
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (!vis[i][j]) {
const q = [[i, j, -1, -1]];
vis[i][j] = true;
for (const [x, y, px, py] of q) {
for (let k = 0; k < 4; k++) {
const [nx, ny] = [x + dirs[k], y + dirs[k + 1]];
if (nx >= 0 && nx < m && ny >= 0 && ny < n) {
if (grid[nx][ny] !== grid[x][y] || (nx === px && ny === py)) {
continue;
}
if (vis[nx][ny]) {
return true;
}
q.push([nx, ny, x, y]);
vis[nx][ny] = true;
}
}
}
}
}
}
return false;
};