bfs算法超时

bfs 算法超时


问题链接:
https://leetcode-cn.com/problems/minesweeper/
问题描述:image-20200830101348413
AC代码:
class Solution {

public:
    struct Node{
        int x;
        int y;
        Node(int x,int y):x(x),y(y){};
    };

    int vis[57][57];
    int dir_x[8] = {-1,-1,-1,0,0,1,1,1};
    int dir_y[8] = {-1,0,1,-1,1,-1,0,1};

    bool checkInside(int x,int y, vector<vector<char>>& board){
        if(x < board.size()  && x >= 0 && y < board[x].size() && y>= 0){
            return true;
        }
        return false;
    }

    int checkAround(int x,int y,vector<vector<char>>& board){
        int ans = 0;
        for(int i=0;i<8;i++){
            int x_new = x + dir_x[i];
            int y_new = y + dir_y[i];
            if(checkInside(x_new, y_new, board)&&board[x_new][y_new]=='M'){
                ans++;
            }
        }
        return ans;
    }

    vector<vector<char>> updateBoard(vector<vector<char>>& board, vector<int>& click) {
        memset(vis,0,sizeof(vis));

        int x = click[0];
        int y = click[1];
        int cnt = 0;

        if(board[x][y] == 'M'){
            board[x][y] = 'X';
        }
        else{
            queue<Node>q;
            q.push(Node(x,y));
            while(!q.empty()){
                Node temp = q.front();
                q.pop();
                //vis[temp.x][temp.y] = 1;
                int boomNumber = checkAround(temp.x,temp.y,board);
                if(boomNumber!=0){
                    board[temp.x][temp.y] = (char)(boomNumber+'0');
                }
                else{
                    board[temp.x][temp.y] = (char)'B';
                    for(int i=0;i<8;i++){
                        int xx = temp.x + dir_x[i];
                        int yy = temp.y + dir_y[i];
                        if(checkInside(xx,yy,board)&&vis[xx][yy]==0){
                            vis[xx][yy]=1;
                            q.push(Node(xx,yy));
                        }
                    }
                }
            }
        }
        return board;
    }
};
问题思考:

本题是一个简单的bfs的模板问题,但是第一次提交出现了超时的情况,出现这种问题的原因的就是,搜索过程中visit数组标记的时机选择错误。正确的做法,应该是在每一个节点入队之前进行标记,而不是出队(注释)之后标记。如果选择在出队之后标记,一个节点会在遍历到之前,被可达节点多次加入队列,从而形成较大的时间复杂度。

posted @ 2020-08-30 10:30  火车不是推的  阅读(231)  评论(0编辑  收藏  举报