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;
        }
    }
  • 相关阅读:
    函数定义、调用
    条件语句和循环语句
    eclipse中安装pydev插件出现duplicate location
    编码类型
    除法
    数据类型
    命令和python模式转换
    前言
    SpringMVC_json
    解决eclipse中Tomcat服务器的server location选项不能修改的问题
  • 原文地址:https://www.cnblogs.com/271934Liao/p/7240452.html
Copyright © 2011-2022 走看看