leetcode Number of Islands

class Solution {
public:
    const int dir[4][2] = {{-1,0},{1,0},{0,-1},{0,1}};
    bool valid(int x, int y, int h, int w, vector<vector<char> >&grid){
        return x >= 0 && x < h && y >= 0 && y < w && grid[x][y] == '1';
    }
    int numIslands(vector<vector<char>> &grid) {
        int h = grid.size();
        if(h == 0){
            return 0;
        }
        int w = grid[0].size();
        if(w == 0){
            return 0;
        }
        int curIsland = 0;
        int checknum = h * w - 1;
        while(checknum >= 0){
            int lineNum = checknum / w;
            int columnNum = checknum % w;
            if(grid[lineNum][columnNum] != '1'){//visited
                checknum--;
                continue;
            }
            queue<pair<int,int> >qr;
            qr.push(make_pair(lineNum, columnNum));
            grid[lineNum][columnNum] = '0';
            while(!qr.empty()){
                pair<int,int> tmpp = qr.front();
                qr.pop();
                for(int i = 0; i < 4; ++i){
                    int tmpx = tmpp.first + dir[i][0];
                    int tmpy = tmpp.second + dir[i][1];
                    if(valid(tmpx, tmpy, h, w, grid)){
                        qr.push(make_pair(tmpx, tmpy));
                        grid[tmpx][tmpy] = '0';
                    }
                }
            }
            curIsland++;
            checknum--;
        }
        return curIsland;
    }
};

错误:矩阵中的每个格子加入队列前就要修改状态(从’1’到’0’)否则后面的bfs过程中会出现重复添加的情况

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值