forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0200-number-of-islands.ts
54 lines (45 loc) · 1.17 KB
/
0200-number-of-islands.ts
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
//BFS way to solve this
constbfs=(grid,r,c)=>{
const[ROWS,COLS]=[grid.length,grid[0].length];
constdirections=[
[-1,0],
[1,0],
[0,-1],
[0,1],
];
letqueue=[[r,c]];
//marks as visited
grid[r][c]='0';
while(queue.length>0){
//dequeues the first element(current)
let[cr,cc]=queue.shift();
directions.forEach(([dr,dc])=>{
let[nr,nc]=[cr+dr,cc+dc];
if(
!(
nr<0||
nc<0||
nr>=ROWS||
nc>=COLS||
grid[nr][nc]==='0'
)
){
queue.push([nr,nc]);
grid[nr][nc]='0';
}
});
}
};
functionnumIslands(grid: string[][]): number{
const[ROWS,COLS]=[grid.length,grid[0].length];
letislands=0;
for(leti=0;i<ROWS;i++){
for(letj=0;j<COLS;j++){
if(grid[i][j]==='1'){
bfs(grid,i,j);
islands++;
}
}
}
returnislands;
}