在v2ex上看到有人提到了这个,感觉挺简单的,没忍住还是试一下....
基本的染色法。
AC代码:
public class Solution { /** * @param grid a boolean 2D matrix * @return an integer */ public int numIslands(boolean[][] grid) { int res=0; for(int i=0;i<grid.length;i++){ for(int j=0;j<grid[i].length;j++){ if(grid[i][j]){ res++; solve(grid,i,j); } } } return res; } private void solve(boolean[][] grid,int x,int y){ if(x<0 || x>=grid.length || y<0 || y>=grid[x].length) return ; if(!grid[x][y]) return ; grid[x][y]=false; solve(grid,x+1,y); solve(grid,x-1,y); solve(grid,x,y+1); solve(grid,x,y-1); } }
题目来源: http://www.lintcode.com/zh-cn/problem/number-of-islands/