LeetCode -- Number of Islands
Problem description:
Given a 2d grid map of '1' s (land) and '0' s (water), count the number of islands. an island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. you may assume all four edges of the grid are all surrounded by water.
Example 1:
11110
11010
11000
00000
Answer: 1
Example 2:
11000
11000
00100
00011
Answer: 3
Given a two-dimensional array grid, 1 indicates land, 0 indicates the ocean, and the number of islands is obtained. The islands are defined as: the upper and lower sides of the ocean or beyond the boundary (outside the grid ).
For example
11000
11000
00100
00011
For this two-dimensional array
11
11
It forms an island.
1
Constitute an island; the last
11
It constitutes another island with three islands in total.
Ideas:
This question is about DFS:
1. initialize a flag array [,]
2. traverse the grid [,]. If the current value is '1', the DFS is marked from the current position up, down, left, and right (note that the cross-border is determined ), if the next position is '1', flag [row, col] = true.
In this way, DFS ensures that all reachable '1' is marked in the flag.
3. When traversing grid [,], find the next unmarked '1' and enter DFS for marking.
4. The number of rounds marked indicates the number of islands.
Implementation Code:
public class Solution { public int NumIslands(char[,] grid) { var row = grid.GetLength(0); var col = grid.GetLength(1); var flag = new bool[row, col]; var count = 0; for(var i = 0;i < row; i++){ for(var j = 0;j < col; j++){ if(grid[i,j] == '1' && !flag[i,j]){ count ++; Mark(ref flag, grid, i, j); } } } return count; } private void Mark(ref bool[,] flag, char[,] grid, int r, int c) { var row = flag.GetLength(0); var col = flag.GetLength(1); if(r < 0 || c < 0 || r >= row || c >= col || grid[r,c] == '0' ||flag[r,c]){ return; } flag[r,c] = true; Mark(ref flag, grid, r + 1, c); Mark(ref flag, grid, r - 1, c); Mark(ref flag, grid, r, c + 1); Mark(ref flag, grid, r, c - 1); }}