关闭

Number of Islands

112人阅读 评论(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

Credits:

Special thanks to @mithmatt for adding this problem and creating all test cases.

思路:就是遍历每一个1的点,做dfs,然后把所有相邻的点全部变成不为1的点,这样count出来也就是做几次dfs了,就有几个island。

public class Solution { 
    public int numIslands(char[][] grid) { 
        if(grid == null || grid.length == 0) return 0; 
        int m = grid.length; 
        int n = grid[0].length; 
        int count = 0; 
        for(int i=0; i<m; i++){ 
            for(int j=0; j<n; j++){ 
                if(grid[i][j] == '1'){ 
                    count++; 
                    dfs(grid, i, j); 
                } 
            } 
        } 
        return count; 
    } 
      
    public void dfs(char[][] grid, int i, int j){ 
        if(i<0 || i>=grid.length || j<0 || j>=grid[0].length || grid[i][j] == '0'){ 
            return; 
        } 
        if(grid[i][j] == '1'){ 
            grid[i][j] = '2'; 
            dfs(grid, i-1, j); 
            dfs(grid, i+1, j); 
            dfs(grid, i, j-1); 
            dfs(grid, i, j+1); 
        } 
    } 
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:110286次
    • 积分:4882
    • 等级:
    • 排名:第6069名
    • 原创:394篇
    • 转载:13篇
    • 译文:0篇
    • 评论:1条
    最新评论