LeetCode 200:Number of Islands

LeetCode 200:Number of Islands

题意描述

给定二维地图“ 1”(土地)和“ 0”(水),计算岛屿的数量。一个岛屿被水包围,是通过水平或垂直连接相邻的陆地而形成的。您可以假设网格的所有四个边缘都被水包围。

测试用例

Example 1:

Input:
11110
11010
11000
00000

Output: 1

Example 2:

Input:
11000
11000
00100
00011

Output: 3

解题思路

一、思路一

遍历数组,当遇到1时,向四周遍历,直到遇到0。当四周都遇到0时,说明已经遍历一个完整的岛屿,岛屿数量+1

	    private int cols;
        private int rows;
        public int numIslands(char[][] grid) {
            if(grid == null || grid.length == 0) return 0;
            rows = grid.length;
            cols = grid [0].length;
            int count = 0;
            boolean[][] flag = new boolean[rows][cols];	//记录已经遍历的岛屿
            for(int i=0;i<rows;i++){
                for(int j=0;j<cols;j++){
                    if(grid[i][j] == '1' && !flag[i][j]){	//当遇到岛屿,并且没有遍历时
                        DFS(grid,i,j,flag);
                        count++;
                    }
                }
            }
            return count;
        }
        private void DFS(char[][] grid,int i,int j,boolean[][] flag){
            if(i<0||i>=rows||j<0||j>=cols||grid[i][j] != '1'||flag[i][j] == true) return;
            flag[i][j] = true;	//当前部分已经遍历
            DFS(grid, i+1,j,flag);
            DFS(grid, i-1,j,flag);
            DFS(grid, i,j+1,flag);
            DFS(grid, i,j-1,flag);
        }

二、思路二

借助队列,将当前位置加入队列,如果当前位置不为0,并且没有被访问过,就将四周位置加入队列。

当队列为空时,说明已经遍历了整个土地,count++。

    private int rows;
        private int cols;
        private int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};//快速计算四周位置
        public int numIslands(char[][] grid) {
            if (grid == null || grid.length == 0) return 0;
            rows = grid.length;
            cols = grid[0].length;
            boolean[][] flag = new boolean[rows][cols];
            Queue<int[]> queue = new LinkedList<>();
            int count = 0;
            for (int i = 0; i < rows; i++) {
                for (int j = 0; j < cols; j++) {
                    if (grid[i][j] == '1' && !flag[i][j]) {
                        queue.add(new int[]{i, j});	//当前位置入队列
                        flag[i][j] = true;//标记访问
                        BFS(grid, queue, flag);
                        count++;
                    }
                }
            }

            return count;
        }

        private void BFS(char[][] nums, Queue<int[]> queue, boolean[][] flag) {
            while (!queue.isEmpty()) {	//队列为空,说明访问完毕整个土地
                int[] cur = queue.poll();	//出队列
                for (int[] dir : dirs) {
                    //计算四周位置
                    int x = cur[0] + dir[0];
                    int y = cur[1] + dir[1];
                    if (x < 0 || x >= rows || y < 0 || y >= cols || flag[x][y] || nums[x][y] == '0')
                        continue;
                    flag[x][y] = true;
                    queue.offer(new int[]{x, y});	//四周入队列
                }
            }
        }
posted @ 2020-05-23 23:10  灵图  阅读(115)  评论(0编辑  收藏  举报