zoukankan      html  css  js  c++  java
  • 200. Number of Islands

    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:

    Input:
    11110
    11010
    11000
    00000
    
    Output: 1
    

    Example 2:

    Input:
    11000
    11000
    00100
    00011
    
    Output: 3

    dfs+visited数组。遍历数组中每一个元素,如果为1且没有visited,调用dfs对其上下左右进行dfs。

    dfs的返回条件是不为1或者已经visited,或者下标越界

    注意corner case(如,输入为空数组)

    时间:O(M*N),空间:worst case O(M*N) (if matrix is filled with islands '1' where dfs goes M*N deep)

    class Solution {
        boolean[][] visited;
            
        public int numIslands(char[][] grid) {
            if(grid == null || grid.length == 0) return 0;
            
            int m = grid.length, n = grid[0].length, res = 0;
            visited = new boolean[m][n];
            for(int i = 0; i < m; i++) {
                for(int j = 0; j < n; j++) {
                    if(grid[i][j] == '1' && visited[i][j] == false) {
                        res++;
                        dfs(grid, i, j, visited);
                    }
                }
            }
            return res;
        }
        
        public void dfs(char[][] grid, int row, int col, boolean[][] visited) {
            if(row < 0 || row > grid.length - 1 || col < 0 || col > grid[0].length - 1)
                return;
            if(grid[row][col] == '0' || visited[row][col] == true)
                return;
            visited[row][col] = true;
            
            dfs(grid, row+1, col, visited);
            dfs(grid, row-1, col, visited);
            dfs(grid, row, col+1, visited);
            dfs(grid, row, col-1, visited);
        }
    }
  • 相关阅读:
    第四篇博客
    第三篇博客
    第二篇博客
    DS博客作业04--图
    DS博客作业03--树
    DS博客作业02--栈和队列
    C博客作业05--指针
    C博客作业04-数组
    C语言博客作业03--函数
    C语言博客作业02--循环结构
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10039911.html
Copyright © 2011-2022 走看看