200. Number of Islands
Tags:
Medium
Skills:
BFS
June 24, 2025
04:32 AM
No headings found
Loading content...
Related Posts
Leetcode
No headings found
Related Posts
Leetcode
Solution - BFS
1function numIslands(grid: string[][]): number {
2 let rows = grid.length;
3 let cols = grid[0].length;
4 let directions = [
5 [1, 0], [-1, 0], [0, 1], [0, -1]
6 ]
7 let island = 0;
8
9 function bfs(row: number, col: number): void {
10 let queue: [number, number][] = [[row, col]];
11 grid[row][col] = '0'
12
13 while (queue.length > 0) {
14 const [r, c] = queue.shift()!;
15
16 for (const [dr, dc] of directions) {
17 const new_r = r + dr;
18 const new_c = c + dc;
19
20 if (new_r >= 0 && new_r < rows && new_c >= 0 && new_c < cols && grid[new_r][new_c] === '1') {
21 grid[new_r][new_c] = '0';
22 queue.push([new_r, new_c])
23 }
24 }
25
26 }
27 }
28
29 for (let i = 0; i < rows; i++) {
30 for (let j = 0; j < cols; j++) {
31 if (grid[i][j] === '1') {
32 bfs(i, j);
33 island++
34 }
35 }
36 }
37
38 return island;
39};