Middle-题目80:200. Number of Islands

原创 2016年05月31日 17:00:18

题目原文:
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

相关文章推荐

[startrelatedarticles]

{relatedtitle}

{relateddes}
[endrelatedarticles] [startrelatedarticlesdownload]

{relatedtitle}

  • {relateposttime}
  • {relatesize}
  • 下载
[endrelatedarticlesdownload] [startrelatedarticlesad1]

{relatedtitle}

{relateddes}
[endrelatedarticlesad1] [startrelatedarticlesad2] [endrelatedarticlesad2]
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)