LintCode:岛屿的个数

来源:互联网 发布:龙腾世纪3优化怎么样 编辑:程序博客网 时间:2024/06/12 01:16

一.题目描述

给一个01矩阵,求不同的岛屿的个数。0代表海,1代表岛,如果两个1相邻,那么这两个1属于同一个岛。我们只考虑上下左右为相邻。


二.解题思路和代码

暂时只能想到递归实现了,遍历数组,当遇到数字1的时候岛屿的个数加1,同时对这个点的上下左右进行递归,把同属一个岛的点都置为0(题中给的是boolean数组)。         

public class Solution {    /**     * @param grid a boolean 2D matrix     * @return an integer     */         int count = 0 ;    boolean[][] temp = null;    public int numIslands(boolean[][] grid) {        // Write your code here        temp = grid;                for(int i = 0 ; i < temp.length ; i ++){            for(int j = 0 ; j < temp[0].length ; j++){                if(temp[i][j]){                    count++;                    travel(i,j);                }                           }        }               return count;    }        private void travel(int i , int j){                temp[i][j] = false;                      if(i-1>=0 && temp[i-1][j]){            travel(i-1,j);        }                if(i+1<=temp.length-1 && temp[i+1][j]){            travel(i+1,j);        }                if(j-1>=0 && temp[i][j-1]){            travel(i,j-1);        }                if(j+1<=temp[0].length-1 && temp[i][j+1]){            travel(i,j+1);        }    }}

结果如下:



0 0
原创粉丝点击