• [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;
        }
    }
  • 相关阅读:
    常见的等待事件如何处理
    oracle常见的等待事件
    12c建立物化视图出现ORA-23319错误
    ORA-07445: exception encountered: core dump [qsmmixGetIdxKeyStats()+231] [SIGSEGV] [ADDR:0x8] [PC:0x58AE44F] [Address not mapped to object] []
    Idea的Debug调试快捷键
    C# 程序禁止重复启动
    C#.Net与SQLServer时间范围的最小值最大值
    MySQL-8.0.20
    Flask框架
    Docker常用命令
  • 原文地址:https://www.cnblogs.com/271934Liao/p/7240452.html
Copyright © 2020-2023  润新知