lintcode-easy-Number of Islands
Posted 哥布林工程师
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lintcode-easy-Number of Islands相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章