Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commita817422

Browse files
committed
Create: 200-Number-of-Islands.ts
1 parentd3e1f01 commita817422

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

‎typescript/200-Number-of-Islands.ts

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
//BFS way to solve this
2+
constbfs=(grid,r,c)=>{
3+
const[ROWS,COLS]=[grid.length,grid[0].length];
4+
5+
constdirections=[
6+
[-1,0],
7+
[1,0],
8+
[0,-1],
9+
[0,1],
10+
];
11+
12+
letqueue=[[r,c]];
13+
14+
//marks as visited
15+
grid[r][c]='0';
16+
17+
while(queue.length>0){
18+
//dequeues the first element(current)
19+
let[cr,cc]=queue.shift();
20+
21+
directions.forEach(([dr,dc])=>{
22+
let[nr,nc]=[cr+dr,cc+dc];
23+
if(
24+
!(
25+
nr<0||
26+
nc<0||
27+
nr>=ROWS||
28+
nc>=COLS||
29+
grid[nr][nc]==='0'
30+
)
31+
){
32+
queue.push([nr,nc]);
33+
grid[nr][nc]='0';
34+
}
35+
});
36+
}
37+
};
38+
39+
functionnumIslands(grid:string[][]):number{
40+
const[ROWS,COLS]=[grid.length,grid[0].length];
41+
42+
letislands=0;
43+
44+
for(leti=0;i<ROWS;i++){
45+
for(letj=0;j<COLS;j++){
46+
if(grid[i][j]==='1'){
47+
bfs(grid,i,j);
48+
islands++;
49+
}
50+
}
51+
}
52+
53+
returnislands;
54+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp