-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path200.岛屿数量.js
103 lines (85 loc) · 1.98 KB
/
200.岛屿数量.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/*
* @lc app=leetcode.cn id=200 lang=javascript
*
* [200] 岛屿数量
*/
// @lc code=start
/**
* @param {character[][]} grid
* @return {number}
*/
var numIslands = function(grid) {
//BFS
// let width = grid.length
// if(!width||!grid[0]) return 0
// let length = grid[0].length
// let area = width*length
// let index = 0
// let count = 0
// while(index<area){
// let [x,y] = [index%width,index/width|0]
// if(grid[x][y]==='1'){
// let queue = [[x,y]]
// while(queue.length){
// let [tx,ty] = queue.shift()
// grid[tx][ty] = '0'
// let rx = tx+1
// rx<width && grid[rx][ty] === '1' && queue.push([rx,ty]) && (grid[rx][ty] = '0')
// // console.log(grid)
// let lx = tx-1
// lx>=0 && grid[lx][ty] === '1' && queue.push([lx,ty]) && (grid[lx][ty] = '0')
// // console.log(grid)
// let uy = ty-1
// uy>=0 && grid[tx][uy] === '1' && queue.push([tx,uy]) && (grid[tx][uy] = '0')
// // console.log(grid)
// let dy = ty+1
// dy<length && grid[tx][dy] === '1' && queue.push([tx,dy]) && (grid[tx][dy] = '0')
// // console.log(grid)
// }
// count++
// }
// index++
// }
// return count
//dfs
function dfs(x,y) {
grid[x][y] = '0'
grid[x+1] && grid[x+1][y]==='1' && dfs(x+1,y)
grid[x-1] && grid[x-1][y]==='1' && dfs(x-1,y)
grid[x][y+1] && grid[x][y+1]==='1' && dfs(x,y+1)
grid[x][y-1] && grid[x][y-1]==='1' && dfs(x,y-1)
}
//DFS
let width = grid.length
if(!width||!grid[0]) return 0
let length = grid[0].length
let area = width*length
let index = 0
let count = 0
while(index<area){
let [x,y] = [index%width,index/width|0]
if(grid[x][y]==='1'){
dfs(x,y)
count++
}
index++
}
return count
};
// @lc code=end
// let grid = [
// ["1","1","1","1","0"],
// ["1","1","0","1","0"],
// ["1","1","0","0","0"],
// ["0","0","1","0","0"]
// ]
// // grid = [
// // ["1","1","1"],
// // ["0","1","0"],
// // ["1","1","1"]
// // ]
// let res = numIslands(grid)
// console.log(res)
// 1 0 1
// 1 1 1
// 1 0 1