题解 | #岛屿数量#

岛屿数量

https://www.nowcoder.com/practice/0c9664d1554e466aa107d899418e814e

class Solution {
public:
//0跳,重复跳
    int dirt[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
    void re(vector<vector<char> >& grid, int i, int j){
        grid[i][j] = '0';//1->0

        for(int k=0; k<4; k++){
            int nexti = i+dirt[k][0];
            int nextj = j+dirt[k][1];
            if(nexti>=0 && nexti<grid.size() && nextj>=0 && nextj<grid[0].size() && grid[nexti][nextj]=='1'){
                re(grid, nexti, nextj);
            }
        }
    }
    
    int solve(vector<vector<char> >& grid) {
        int count = 0;
        for(int i=0; i<grid.size(); i++){
            for(int j=0; j<grid[0].size(); j++){
                if(grid[i][j]=='1'){
                    re(grid, i, j);
                    count++;
                }
            }
        }
        return count;

    }
};

回溯部分主要是遍历完一个完整的岛屿,并将遍历到的合法岛屿点置0,故再往下一个岛屿的时候,不会和已经遍历过的岛屿点冲突。

全部评论

相关推荐

07-29 14:09
门头沟学院 Java
我爱o泡我爱o泡o泡果奶ooo
26加瓦鼠鼠:三个offer了,停手吧,回头是岸
OPPO泡池子110人在聊
点赞 评论 收藏
分享
酷酷我灵儿帅:这去不去和线不线下面说实话没啥关系
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务