-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path7.js
51 lines (46 loc) · 892 Bytes
/
7.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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// Title: 섬나라 아일랜드(DFS)
// Time: O(nm)
// Space: O(1)
function main(n, mx) {
const dist = [
[-1, 0],
[-1, 1],
[0, 1],
[1, 1],
[1, 0],
[1, -1],
[0, -1],
[-1, -1],
];
let result = 0;
for (let x = 0; x < n; x++) {
for (let y = 0; y < n; y++) {
if (mx[x][y] === 1) {
dfs(x, y);
result++;
}
}
}
console.log(result);
function dfs(x, y) {
mx[x][y] = 0;
for (let i = 0; i < 8; i++) {
const [dx, dy] = dist[i];
const nx = x + dx;
const ny = y + dy;
if (0 <= nx && nx < n && 0 <= ny && ny < n && mx[nx][ny] === 1) {
dfs(nx, ny);
}
}
}
}
const matrix = [
[1, 1, 0, 0, 0, 1, 0],
[0, 1, 1, 0, 1, 1, 0],
[0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 1, 1],
[1, 1, 0, 1, 1, 0, 0],
[1, 0, 0, 0, 1, 0, 0],
[1, 0, 1, 0, 1, 0, 0],
];
main(7, matrix);