Middle-题目80: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:
11110
11010
11000
00000
Answer: 1
Example 2:
11000
11000
00100
00011
Answer: 3
题目大意:
给出一个矩阵,其中1代表岛,0代表海水,求出有几个岛。
题目分析:
本题是一个标准的不能再标准的dfs问题,从一个未访问的“岛”点开始从四个方向搜索,遇到“海水”或者矩阵边界就退出。
源码:(language:java)

public class Solution {
    public int numIslands(char[][] grid) {
        if (grid.length==0 || grid[0].length==0) 
            return 0;
        int count = 0;
        boolean[][] visited = new boolean[grid.length][grid[0].length];
        for (int i=0; i<grid.length; i++) {
            for (int j=0; j<grid[0].length; j++) {
                if (grid[i][j]=='1' && !visited[i][j]) { 
                    count++;
                    dfs(grid, visited, i, j);
                }
            }
        }
        return count;
    }

    private void dfs(char[][] grid, boolean[][] visited, int row, int col) {
        if (row<0 || row>=grid.length || col<0 || col>=grid[0].length || visited[row][col] || grid[row][col]=='0') // grid[i][j] is out of range
            return; 
        visited[row][col] = true;
        dfs(grid, visited, row-1, col);
        dfs(grid, visited, row+1, col);
        dfs(grid, visited, row, col-1);
        dfs(grid, visited, row, col+1);
    }
}

成绩:
5ms,beats 25.10%,众数3ms,40.17%
Cmershen的碎碎念:
其实本题的算法也适用于计算机图形学中的“颜色填充算法”,其原理一模一样。

阅读更多
版权声明:完整版Leetcode题解请出门左转https://github.com/cmershen1/leetcode/tree/master/docs https://blog.csdn.net/cmershen/article/details/51547258
个人分类: Leetcode
上一篇Middle-题目79:40. Combination Sum II
下一篇Middle-题目81:264. Ugly Number II
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭