Skip to content

Commit bd1540a

Browse files
Jeehay28Jeehay28
authored andcommitted
Add number-of-islands solution in TS
1 parent bf225cf commit bd1540a

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

number-of-islands/Jeehay28.ts

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
// TC: O(n), where N = total number of cells = m * n
2+
// SC: O(n)
3+
4+
function numIslands(grid: string[][]): number {
5+
const sink = (row: number, col: number) => {
6+
visited[row][col] = true;
7+
8+
const dirs = [
9+
[row - 1, col],
10+
[row + 1, col],
11+
[row, col - 1],
12+
[row, col + 1],
13+
];
14+
15+
for (const dir of dirs) {
16+
const [r, c] = dir;
17+
18+
if (r >= 0 && r < grid.length && c >= 0 && c < grid[0].length) {
19+
if (!visited[r][c] && grid[r][c] === "1") {
20+
sink(r, c);
21+
}
22+
}
23+
}
24+
};
25+
26+
let count = 0;
27+
const visited: boolean[][] = Array.from({ length: grid.length }, () =>
28+
Array(grid[0].length).fill(false)
29+
);
30+
31+
for (let i = 0; i < grid.length; i++) {
32+
for (let j = 0; j < grid[0].length; j++) {
33+
if (!visited[i][j] && grid[i][j] === "1") {
34+
count++;
35+
sink(i, j); // // Sink all connected neighboring land cells
36+
}
37+
}
38+
}
39+
40+
return count;
41+
}

0 commit comments

Comments
 (0)