Skip to content

Commit 948aeb6

Browse files
authored
Merge pull request neetcode-gh#93 from anthonysim/asim/islands
Added JS 200 Number of Islands
2 parents 5160466 + 919b07a commit 948aeb6

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

javascript/200-Number-of-Islands.js

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
// Version 1
2+
function explore(grid, r, c, visited) {
3+
const rowInbounds = 0 <= r && r < grid.length;
4+
const colInbounds = 0 <= c && c < grid[0].length;
5+
6+
if (!rowInbounds || !colInbounds) return false;
7+
if (grid[r][c] === '0') return false;
8+
9+
const pos = r + ',' + c;
10+
11+
if (visited.has(pos)) return false;
12+
visited.add(pos);
13+
14+
explore(grid, r - 1, c, visited);
15+
explore(grid, r + 1, c, visited);
16+
explore(grid, r, c - 1, visited);
17+
explore(grid, r, c + 1, visited);
18+
19+
return true;
20+
}
21+
22+
var numIslands = function (grid) {
23+
const visited = new Set();
24+
let count = 0;
25+
26+
for (let r = 0; r < grid.length; r++) {
27+
for (let c = 0; c < grid[0].length; c++) {
28+
if (explore(grid, r, c, visited)) {
29+
count += 1;
30+
}
31+
}
32+
}
33+
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;
61+
};

0 commit comments

Comments
 (0)