BFS+回溯

迷宫问题

http://www.nowcoder.com/questionTerminal/cf24906056f4488c9ddb132f317e03bc

看代码就行啦,很好理解~

#include<iostream>
#include<vector>

using namespace std;
vector<int> drow = {1,0,0,-1};
vector<int> dcol = {0,1,-1,0};
vector<vector<int> > res; 

bool calShorestPath(vector<vector<int> >&grid, int r, int c, int m, int n){
    grid[r][c]=1;
//    cout << "(" << r << "," << c << ")" << endl;
    if(r==m-1&&c==n-1) return true;

    for(int index=0;index<4;index++){
        int nr = r+drow[index];
        int nc = c+dcol[index];
        if(nr>=0&&nr<m&&nc>=0&&nc<n&&grid[nr][nc]==0){
            if (calShorestPath(grid, nr,nc,m,n)){ 
//                cout << "(" << nr << "," << nc << ")" << endl;
                res.insert(res.begin(),{nr,nc});
                return true;
            } 
            grid[nr][nc]=0;
        }
    }
    return false;
}

int main(){
    int m,n;
    while(cin >> m >> n){
        vector<vector<int> > grid(m, vector<int>(n,0));
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                cin >> grid[i][j];
            }
        }
        res.clear();
        calShorestPath(grid, 0, 0, m, n);
        cout << "(0,0)" << endl;
        for(auto i : res){
            cout << "(" << i[0] << "," << i[1] << ")" << endl;
        }
    }
    return 0;
}
全部评论

相关推荐

10-07 23:57
已编辑
电子科技大学 Java
八街九陌:博士?客户端?开发?啊?
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务