[LeetCode]Number of Islands

解题思路:
图的连通性,一次遍历并不能遍历所有的island,要在深度搜索外加一个for循环,并做好被explored的点的标记


class Solution {
public:

    int numIslands(vector<vector<char>>& grid) {
        if(grid.size() == 0 || grid[0].size() == 0) return 0;
        vector<vector<bool> > explored(grid.size(), vector<bool>(grid[0].size(), false));
        vector<vector<int> > direction;
        direction.push_back({0 , 1});
        direction.push_back({1 , 0});
        direction.push_back({0 , -1});
        direction.push_back({-1 , 0});
        printf("dirction OK\n");

        int countIsland = 0;
        int row = grid.size();
        int col = grid[0].size();
        for(int i = 0 ; i < row; ++i){
            for(int j = 0; j < col; ++j){
                if (!explored[i][j] && grid[i][j] == '1'){
                    printf("come int first cell\n");
                    countIsland++;
                    exploreIsland(i, j, grid, explored, direction);
                }
            }
        }

        return countIsland;
    }

    void exploreIsland(int i, int j, vector<vector<char> >& grid, vector<vector<bool> >& explored, vector<vector<int> >& direction){

        if (i < 0 || j < 0 || i >= grid.size() || j >= grid[0].size()) return;
        if (!explored[i][j]){
            if (grid[i][j] == '1'){
                explored[i][j] = true;
                for(int ind = 0; ind < 4; ++ind){
                    int x = i + direction[ind][0];
                    int y = j + direction[ind][1];
                    if (x < 0 || y < 0 || x >= grid.size() || y >= grid[0].size()) continue;

                    if (!explored[x][y] && grid[x][y] == '1'){
                        exploreIsland(x, y, grid, explored, direction);
                    }
                }
            }
        }
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值