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;
        }
    }
  • 相关阅读:
    elasticsearch _bulk api
    elasticsearch _update api 更新部分字段内容
    elasticsearch _create api创建一个不存在的文档
    sql之left join、right join、inner join的区别
    Eclipse FreeMarker 插件安装
    Linux下Tomcat服务器重启与关闭
    SQL JOIN的用法
    HttpClient请求
    Struts2学习笔记
    Tomcat长出现的内存溢出问题
  • 原文地址:https://www.cnblogs.com/271934Liao/p/7240452.html
Copyright © 2011-2022 走看看