深度优先搜索,每次遇到1,则岛的数量+1,从这个1开始找到所有相连的1,将其改为0。
public class Solution { private void dfsSearch(char[,] grid, int i, int j, int rows, int cols) { if (i < 0 || i >= rows || j < 0 || j >= cols) { return; } if (grid[i, j] == '0') { return; } grid[i, j] = '0'; dfsSearch(grid, i + 1, j, rows, cols); dfsSearch(grid, i - 1, j, rows, cols); dfsSearch(grid, i, j + 1, rows, cols); dfsSearch(grid, i, j - 1, rows, cols); } public int NumIslands(char[,] grid) { var rows = grid.GetLength(0); var cols = grid.GetLength(1); if (rows == 0 || cols == 0) { return 0; } int count = 0; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (grid[i, j] == '1') { count++; dfsSearch(grid, i, j, rows, cols); } } } return count; } }