Skip to content

Commit fcababd

Browse files
committed
number of islands solution
1 parent 46ac718 commit fcababd

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

number-of-islands/hyer0705.ts

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
function numIslands(grid: string[][]): number {
2+
const m = grid.length;
3+
const n = grid[0].length;
4+
5+
const LAND = "1";
6+
const WATER = "0";
7+
8+
const visited: boolean[][] = Array.from({ length: m }, () => Array(n).fill(false));
9+
10+
const isValid = (row: number, col: number): boolean => row >= 0 && row < m && col >= 0 && col < n;
11+
12+
const bfs = (row: number, col: number): void => {
13+
const directions = [
14+
[0, 1],
15+
[0, -1],
16+
[1, 0],
17+
[-1, 0],
18+
];
19+
20+
// [row, col][]
21+
const queue: number[][] = [];
22+
23+
visited[row][col] = true;
24+
queue.push([row, col]);
25+
26+
while (queue.length > 0) {
27+
const [cx, cy] = queue.shift()!;
28+
29+
for (const [dx, dy] of directions) {
30+
const [nx, ny] = [cx + dx, cy + dy];
31+
32+
if (isValid(nx, ny) && !visited[nx][ny] && grid[nx][ny] === LAND) {
33+
visited[nx][ny] = true;
34+
queue.push([nx, ny]);
35+
}
36+
}
37+
}
38+
};
39+
40+
let island = 0;
41+
42+
for (let i = 0; i < m; i++) {
43+
for (let j = 0; j < n; j++) {
44+
if (grid[i][j] === LAND && !visited[i][j]) {
45+
island++;
46+
bfs(i, j);
47+
}
48+
}
49+
}
50+
51+
return island;
52+
}

0 commit comments

Comments
 (0)