Leetcode 200: Number of Islands
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
1 public class Solution { 2 public int NumIslands(char[,] grid) { 3 if (grid == null) return 0; 4 5 int rows = grid.GetLength(0), cols = grid.GetLength(1); 6 if (rows == 0 || cols == 0) return 0; 7 8 int count = 0; 9 var dirs = new int[,] {{0, 1}, {0, -1}, {-1, 0}, {1, 0}}; 10 11 for (int i = 0; i < rows; i++) 12 { 13 for (int j = 0; j < cols; j++) 14 { 15 if (grid[i, j] == '1') 16 { 17 count++; 18 19 // bfs 20 var queue = new Queue<Tuple<int, int>>(); 21 queue.Enqueue(new Tuple<int, int>(i, j)); 22 23 while (queue.Count > 0) 24 { 25 var node = queue.Dequeue(); 26 grid[node.Item1, node.Item2] = '2'; 27 28 for (int k = 0; k < 4; k++) 29 { 30 int ni = node.Item1 + dirs[k, 0], nj = node.Item2 + dirs[k, 1]; 31 32 if (ni >= 0 && ni < rows && nj >= 0 && nj < cols && grid[ni, nj] == '1') 33 { 34 grid[ni, nj] = '2'; 35 queue.Enqueue(new Tuple<int, int>(ni, nj)); 36 } 37 } 38 } 39 } 40 } 41 } 42 43 return count; 44 } 45 }

浙公网安备 33010602011771号