433-岛屿的个数

来源:互联网 发布:沪深大宗交易数据 编辑:程序博客网 时间:2024/04/30 06:39

4.11

数组统一赋值的函数Arrays.fill();

感觉自己的想法很野啊,用总的点的个数去减。

就是要注意边界值,数组是从下标0开始的,一定要注意。

public class Solution {    /**     * @param grid a boolean 2D matrix     * @return an integer     */   public static int numIslands(boolean[][] grid) {//flag数组用来存储是否访问过了 int N = grid.length;if(N <= 0){    return 0;}//行数int M = grid[0].length;if(M <=0){    return 0;}//列数int count = M*N;boolean[][] flag = new boolean[N][M];for(int i = 0;i < N;i++){for(int j = 0;j < M;j++){if(flag[i][j] == false){flag[i][j] =true;if(grid[i][j] == false){count --;}else{count = around(i,j,grid,flag,M,N,count);}}}}return count;// Write your code here}//给定一个点,判断它的四周public static int around(int i,int j,boolean[][] grid,boolean[][] flag,int m,int n,int count) {        //上边if(i-1 >=0 && flag[i-1][j] ==false){flag[i-1][j] = true;if(grid[i-1][j] == true){count --;count = around(i-1,j,grid,flag,m,n,count);}else{count --;}}//下边if(i+1 < n && flag[i+1][j] ==false){flag[i+1][j] = true;if(grid[i+1][j] == true){count --;count = around(i+1,j,grid,flag,m,n,count);}else{count --;}}//左边if(j-1 >=0 && flag[i][j-1] ==false){flag[i][j-1] = true;if(grid[i][j-1] == true){count --;count = around(i,j-1,grid,flag,m,n,count);}else{count --;}}//右边if(j+1 < m && flag[i][j+1] ==false){flag[i][j+1] = true;if(grid[i][j+1] == true){count --;count = around(i,j+1,grid,flag,m,n,count);}else{count --;}}return count;    }}


0 0
原创粉丝点击