-
-
Notifications
You must be signed in to change notification settings - Fork 164
/
Copy pathnumberOfIslands.js
84 lines (71 loc) · 2.03 KB
/
numberOfIslands.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
//DFS: TC: O(rows * cols) SC: O(rows * cols)
function numIslands1(grid) {
let rows = grid.length, cols = grid[0].length;
let islandsCount = 0;
for(let r=0; r< rows; r++) {
for(let c=0; c<cols; c++) {
if(grid[r][c] === '1') {
islandsCount++;
dfs(grid, r, c);
}
}
}
return islandsCount;
}
function dfs(grid, row, col){
if(row < 0 || row >= grid.length || col < 0 || col >= grid[0].length || grid[row][col] === '0') return;
grid[row][col] = '0';
//down,top,right and left
dfs(grid, row+1, col);
dfs(grid, row-1, col);
dfs(grid, row, col+1);
dfs(grid, row, col-1);
}
//BFS: TC: O(rows * cols) SC: O(min(rows * cols))
function numIslands2(grid) {
let rows = grid.length, cols = grid[0].length;
let islandsCount = 0;
for(let r=0; r< rows; r++) {
for(let c=0; c<cols; c++) {
if(grid[r][c] === '1') {
islandsCount++;
bfs(grid, r, c);
}
}
}
return islandsCount;
}
function bfs(grid, row, col){
let queue = [[row,col]];
grid[row][col] = '0';
while(queue.length){
const [r, c] = queue.shift();
const directions = [[-1,0],[0,-1],[0,1],[1,0]];
for (const [dr,dc] of directions) {
row = r+dr;
col = c+dc;
if(row >=0 && row < grid.length && col >=0 && col < grid[0].length && grid[row][col] === '1'){
queue.push([row, col]);
grid[row][col] = '0';
}
}
}
}
let grid1 = [
["0","1","1","1","0"],
["0","1","0","1","0"],
["0","1","0","1","0"],
["0","1","0","0","0"]
];
let grid11 = JSON.parse(JSON.stringify(grid1));
console.log(numIslands1(grid1));
console.log(numIslands2(grid11));
let grid2 = [
['1','1','0','1','1'],
['1','1','0','0','0'],
['0','0','1','0','1'],
['0','0','0','1','1']
];
let grid22 = JSON.parse(JSON.stringify(grid2));
console.log(numIslands1(grid2));
console.log(numIslands2(grid22));