Skip to content

Commit 6a60cda

Browse files
authored
Create 1559-detect-cycles-in-2d-grid.js
1 parent 94fe41d commit 6a60cda

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

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

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/**
2+
* @param {character[][]} grid
3+
* @return {boolean}
4+
*/
5+
const containsCycle = function (grid) {
6+
const wholePath = (r, c, letter, component, last = [-1, -1]) => {
7+
const dirs = [
8+
[0, -1],
9+
[0, 1],
10+
[-1, 0],
11+
[1, 0],
12+
]
13+
const tmp = grid[r][c]
14+
grid[r][c] = component
15+
const nextSteps = dirs
16+
.map((x) => [x[0] + r, x[1] + c])
17+
.filter(
18+
(x) =>
19+
x[0] >= 0 && x[0] < grid.length && x[1] >= 0 && x[1] < grid[0].length
20+
)
21+
for (let step of nextSteps) {
22+
if (step[0] === last[0] && last[1] === step[1]) {
23+
continue
24+
}
25+
if (grid[step[0]][step[1]] === component) {
26+
return true
27+
}
28+
if (grid[step[0]][step[1]] === letter) {
29+
let outcome = wholePath(step[0], step[1], letter, component, [r, c])
30+
if (outcome) {
31+
return true
32+
}
33+
}
34+
}
35+
return false
36+
}
37+
38+
let component = 1
39+
for (let r = 0; r < grid.length; r++) {
40+
for (let c = 0; c < grid[0].length; c++) {
41+
const letter = grid[r][c]
42+
if (typeof letter === 'string') {
43+
grid[r][c] = component
44+
const outcome = wholePath(r, c, letter, component)
45+
if (outcome) {
46+
return true
47+
}
48+
component++
49+
}
50+
}
51+
}
52+
return false
53+
}

0 commit comments

Comments
 (0)