标签:
Given a boolean 2D matrix, find the number of islands.
Given graph:
[
[1, 1, 0, 0, 0],
[0, 1, 0, 0, 1],
[0, 0, 0, 1, 1],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 1]
]
return 3
.
public class Solution { /** * @param grid a boolean 2D matrix * @return an integer */ public int numIslands(boolean[][] grid) { // Write your code here if(grid == null || grid.length == 0 || grid[0] == null || grid[0].length == 0) return 0; int m = grid.length; int n = grid[0].length; int result = 0; for(int i = 0; i < m; i++){ for(int j = 0; j < n; j++){ if(grid[i][j]){ result++; flood(grid, i, j); } } } return result; } public void flood(boolean[][] grid, int i, int j){ grid[i][j] = false; int m = grid.length; int n = grid[0].length; if(i - 1 >= 0 && grid[i - 1][j]) flood(grid, i - 1, j); if(i + 1 < m && grid[i + 1][j]) flood(grid, i + 1, j); if(j - 1 >= 0 && grid[i][j - 1]) flood(grid, i, j - 1); if(j + 1 < n && grid[i][j + 1]) flood(grid, i, j + 1); return; } }
lintcode-easy-Number of Islands
标签:
原文地址:http://www.cnblogs.com/goblinengineer/p/5237183.html