码迷,mamicode.com
首页 > 其他好文 > 详细

200. Number of Islands - Medium

时间:2018-11-29 20:14:39      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:code   you   fill   HERE   数组   medium   number   不为   i++   

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);
    }
}

 

200. Number of Islands - Medium

标签:code   you   fill   HERE   数组   medium   number   不为   i++   

原文地址:https://www.cnblogs.com/fatttcat/p/10039911.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!