leetcode 解题思路

FLAG必经之路

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

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


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013325815/article/details/52368243
个人分类: DFS
上一篇Sparse Matrix Multiplication
下一篇Encode and Decode Strings
想对作者说点什么? 我来说一句

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

关闭
关闭