原题链接在这里:https://leetcode.com/problems/number-of-islands/
若是碰到一个1, res++, 用DFS把与它相连的1 都换成0. 继续扫描,最后算出能有多少个 单独的 1.
AC Java:
1 public class Solution { 2 public int numIslands(char[][] grid) { 3 if(grid == null || grid.length == 0 || grid[0].length == 0){ 4 return 0; 5 } 6 int res = 0; 7 for(int i = 0; i<grid.length; i++){ 8 for(int j = 0; j<grid[0].length; j++){ 9 if(grid[i][j] == ‘1‘){ 10 res++; 11 replace(grid,i,j); 12 } 13 } 14 } 15 return res; 16 } 17 private void replace(char[][] grid, int i, int j){ 18 if(i<0 || i>=grid.length || j<0 || j>=grid[0].length || grid[i][j] != ‘1‘){ 19 return; 20 } 21 grid[i][j] = ‘0‘; 22 replace(grid,i-1,j); 23 replace(grid,i+1,j); 24 replace(grid,i,j-1); 25 replace(grid,i,j+1); 26 } 27 }
原文:http://www.cnblogs.com/Dylan-Java-NYC/p/4886884.html