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

Commita39bddc

Browse files
committed
added alternate version
1 parentae4ffb6 commita39bddc

File tree

1 file changed

+28
-1
lines changed

1 file changed

+28
-1
lines changed

‎javascript/200-Number-of-Islands.js‎

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
// Version 1
12
functionexplore(grid,r,c,visited){
23
constrowInbounds=0<=r&&r<grid.length;
34
constcolInbounds=0<=c&&c<grid[0].length;
@@ -18,7 +19,6 @@ function explore(grid, r, c, visited) {
1819
returntrue;
1920
}
2021

21-
2222
varnumIslands=function(grid){
2323
constvisited=newSet();
2424
letcount=0;
@@ -31,4 +31,31 @@ var numIslands = function (grid) {
3131
}
3232
}
3333
returncount;
34+
};
35+
36+
// Version 2 (Easier to understand/read)
37+
functiondfs(grid,i,j){
38+
if(i<0||i>=grid.length||j<0||j>=grid[0].length||grid[i][j]==="0"){
39+
return;
40+
}
41+
42+
grid[i][j]="0";
43+
dfs(grid,i+1,j);
44+
dfs(grid,i-1,j);
45+
dfs(grid,i,j+1);
46+
dfs(grid,i,j-1);
47+
}
48+
49+
varnumIslands=function(grid){
50+
letcount=0;
51+
52+
for(leti=0;i<grid.length;i++){
53+
for(letj=0;j<grid[0].length;j++){
54+
if(grid[i][j]==="1"){
55+
count+=1;
56+
dfs(grid,i,j);
57+
}
58+
}
59+
}
60+
returncount;
3461
};

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp