Skip to content

Commit 919b07a

Browse files
committed
added alternate version
1 parent c884c69 commit 919b07a

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
function explore(grid, r, c, visited) {
23
const rowInbounds = 0 <= r && r < grid.length;
34
const colInbounds = 0 <= c && c < grid[0].length;
@@ -18,7 +19,6 @@ function explore(grid, r, c, visited) {
1819
return true;
1920
}
2021

21-
2222
var numIslands = function (grid) {
2323
const visited = new Set();
2424
let count = 0;
@@ -31,4 +31,31 @@ var numIslands = function (grid) {
3131
}
3232
}
3333
return count;
34+
};
35+
36+
// Version 2 (Easier to understand/read)
37+
function dfs(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+
var numIslands = function (grid) {
50+
let count = 0;
51+
52+
for (let i = 0; i < grid.length; i++) {
53+
for (let j = 0; j < grid[0].length; j++) {
54+
if (grid[i][j] === "1") {
55+
count += 1;
56+
dfs(grid, i, j);
57+
}
58+
}
59+
}
60+
return count;
3461
};

0 commit comments

Comments
 (0)