Skip to content

Commit d0fba6c

Browse files
authored
Update 1559-detect-cycles-in-2d-grid.js
1 parent 6a60cda commit d0fba6c

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

1559-detect-cycles-in-2d-grid.js

+48
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,51 @@
1+
/**
2+
* @param {character[][]} grid
3+
* @return {boolean}
4+
*/
5+
const containsCycle = function (grid) {
6+
const dirs = [
7+
[1, 0],
8+
[-1, 0],
9+
[0, 1],
10+
[0, -1],
11+
]
12+
const rows = grid.length
13+
const cols = (grid[0] || []).length
14+
const vis = Array.from({ length: rows }, () => Array(cols).fill(false))
15+
let res = false
16+
const dfs = (i, j, prevR, prevC, char) => {
17+
vis[i][j] = true
18+
for (let d of dirs) {
19+
const r = i + d[0]
20+
const c = j + d[1]
21+
if (r >= 0 && r < rows && c >= 0 && c < cols) {
22+
if (!(r == prevR && c === prevC)) {
23+
if (grid[r][c] === char) {
24+
if (!vis[r][c]) {
25+
if (dfs(r, c, i, j, char)) return true
26+
} else {
27+
if (prevR !== -1 && prevC !== -1) return true
28+
}
29+
}
30+
}
31+
}
32+
}
33+
return false
34+
}
35+
36+
for (let i = 0; i < rows; i++) {
37+
for (let j = 0; j < cols; j++) {
38+
if (!vis[i][j]) {
39+
res |= dfs(i, j, -1, -1, grid[i][j])
40+
}
41+
if (res) return true
42+
}
43+
}
44+
return res
45+
}
46+
47+
// another
48+
149
/**
250
* @param {character[][]} grid
351
* @return {boolean}

0 commit comments

Comments
 (0)