[LeetCode] Number of Islands

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’,就递归将其左右上下为1的元素全部标记为‘0’,计数加1。(之前做的是积水,还包括对角处)。下面是代码;

class Solution {
public:
    int numIslands(vector<vector<char>> &grid) {
        int m = grid.size();
        if(m==0){
            return 0;
        }
        int n = grid[0].size();
        if(n==0){
            return 0;
        }
        
        int result = 0;
        for(int i=0; i<m; i++){
            for(int j=0; j<n; j++){
                if(grid[i][j] == '1'){
                    result++;
                    markRead(grid, m, n, i, j);
                }
            }
        }
        return result;
    }
    
    void markRead(vector<vector<char>> &grid, int m, int n, int i, int j){
        if(i<0||j<0 || i>=m||j>=n||grid[i][j]=='0'){
            return;
        }
        grid[i][j]='0';
        markRead(grid, m, n, i+1, j);
        markRead(grid, m, n, i, j+1);
        markRead(grid, m, n, i-1, j);
        markRead(grid, m, n, i, j-1);
    }
};


0 条评论

    发表评论

    电子邮件地址不会被公开。 必填项已用 * 标注