zoukankan      html  css  js  c++  java
  • [LeetCode] 200. Number of Islands Java

    题目:

    Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

    Example 1:

    11110
    11010
    11000
    00000

    Answer: 1

    Example 2:

    11000
    11000
    00100
    00011

    Answer: 3

    题意及分析:给出一个'1'和‘0’组成的二位矩阵,其中1代表陆地,0代表海洋,四个边界外都是海洋,要求计算有几块岛屿(岛屿定义为这片陆地四周都为海洋)。简单来讲就是要求几块独立的'1'组成的区域。对每个为‘1’的点进行宽度遍历(上下左右四个方向),遍历过的点置为‘2’,防止重复遍历。用quene记录该次遍历需要遍历的点。

    代码:

    public class Solution {
        public int numIslands(char[][] grid) {
            int row = grid.length;
            if(row==0) return 0;
            int col = grid[0].length;
            int count =  0;
            Queue<Integer[]> queue = new LinkedList<>();        ///记录已经被遍历的区域的点索引
            for(int i=0;i<row;i++){
                for(int j=0;j<col;j++){
                    if(grid[i][j]=='1'){      //找到某块为1的区域,遍历过后改为'2'
                        count++;    //每次遇到新的区域便加1
                        Integer[] indexs={i,j};
                        queue.offer(indexs);
                        while(!queue.isEmpty()){
                            Integer[] temp = queue.poll();
                            int m=temp[0],n=temp[1];
                            if(grid[m][n]=='1'){
                                grid[m][n]='2';
                                if(m-1>=0&&grid[m-1][n]=='1'){
                                    Integer[] index = {m-1,n};
                                    queue.offer(index);
                                }
                                if(m+1<row&&grid[m+1][n]=='1'){
                                    Integer[] index = {m+1,n};
                                    queue.offer(index);
                                }
                                if(n-1>=0&&grid[m][n-1]=='1'){
                                    Integer[] index = {m,n-1};
                                    queue.offer(index);
                                }
                                if(n+1<col&&grid[m][n+1]=='1'){
                                    Integer[] index = {m,n+1};
                                    queue.offer(index);
                                }
                            }
                        }
                    }
                }
            }
            return count;
        }
    }
  • 相关阅读:
    496. 下一个更大元素 I
    20200516文献速递
    20200510文献速递
    beta,or, p value计算zscore
    20200503文献速递
    古人以及其他灵长类动物基因组数据
    20200420-0426文献速递
    使用snpflip校正基因组正负链
    使用qqman对曼哈顿图(Manhattan plot )多个显著位点标志不同颜色,拒绝屎一样的绿色
    RAEdb:基于STARR-seq和MPRA数据的enhancers和Epromoters可视化
  • 原文地址:https://www.cnblogs.com/271934Liao/p/7240452.html
Copyright © 2011-2022 走看看