[LintCode] Number of Islands
public int numIslands(boolean[][] grid) { // Write your code here if(grid == null) return 0; int res = 0; for(int i = 0 ; i < grid.length; i++) { for(int j = 0; j < grid[0].length; j++) { if(grid[i][j]) res++; dfs(grid,i,j); } } return res; } public void dfs(boolean[][] m, int i, int j) { if(i < 0 || i >= m.length || j < 0 || j >= m[0].length || !m[i][j]) return; m[i][j] = false; dfs(m, i - 1, j); dfs(m, i, j - 1); dfs(m, i + 1, j); dfs(m, i, j + 1); }
Leave A Comment