Skip to content

Commit ce874ff

Browse files
author
Kohei Asai
authored
200. Number of Islands (axross#122)
1 parent 7b94016 commit ce874ff

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

Diff for: solutions/number_of_islands.ts

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// 200. Number of Islands
2+
// https://leetcode.com/problems/number-of-islands/
3+
export default function numIslands(grid: ("1" | "0")[][]): number {
4+
const width = grid[0] ? grid[0].length : 0;
5+
const height = grid.length;
6+
let islands = 0;
7+
8+
function explore(y: number, x: number): void {
9+
if (grid[y][x] === "0") return;
10+
11+
grid[y][x] = "0";
12+
13+
if (y - 1 >= 0) explore(y - 1, x);
14+
if (y + 1 < height) explore(y + 1, x);
15+
if (x - 1 >= 0) explore(y, x - 1);
16+
if (x + 1 < width) explore(y, x + 1);
17+
}
18+
19+
for (let y = 0; y < height; ++y) {
20+
for (let x = 0; x < width; ++x) {
21+
if (grid[y][x] === "0") continue;
22+
23+
islands += 1;
24+
25+
explore(y, x);
26+
}
27+
}
28+
29+
return islands;
30+
}

Diff for: solutions/number_of_islands_test.ts

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import { test } from "https://deno.land/std/testing/mod.ts";
2+
import { assert } from "https://deno.land/std/testing/asserts.ts";
3+
import numIslands from "./number_of_islands.ts";
4+
5+
test("200. Number of Islands", () => {
6+
assert(
7+
numIslands([
8+
["1", "1", "1", "1", "0"],
9+
["1", "1", "0", "1", "0"],
10+
["1", "1", "0", "0", "0"],
11+
["0", "0", "0", "0", "0"]
12+
]) === 1
13+
);
14+
assert(
15+
numIslands([
16+
["1", "1", "0", "0", "0"],
17+
["1", "1", "0", "0", "0"],
18+
["0", "0", "1", "0", "0"],
19+
["0", "0", "0", "1", "1"]
20+
]) === 3
21+
);
22+
});

0 commit comments

Comments
 (0)