关闭

Middle-题目80:200. Number of Islands

62人阅读 评论(0) 收藏 举报
分类:

题目原文:
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的碎碎念:
其实本题的算法也适用于计算机图形学中的“颜色填充算法”,其原理一模一样。

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:56030次
    • 积分:3202
    • 等级:
    • 排名:第10679名
    • 原创:270篇
    • 转载:53篇
    • 译文:0篇
    • 评论:7条
    文章分类
    最新评论