1255:迷宫问题

题目分析:

  • 找到最短路径,然后输出路径上的所有点
  • 用pre[][]数组存储后面走过的点,然后从后往前遍历(或者从终点开始)

代码如下:

#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>

using namespace std;

#define x first
#define y second
#define pii pair<int,int>
#define el endl
#define mm(a,x) memset(a,x,sizeof a)
#define mk make_pair

const int N = 10;

int n = 5;
int g[N][N];
pii pre[N][N];
int dx[4] = {0,1,0,-1};
int dy[4] = {1,0,-1,0};

void bfs(int sx,int sy){
    mm(pre,-1);
    queue<pii> q;
    q.push(mk(sx,sy));
    pre[sx][sy] = mk(0,0);
    while(q.size()){
        pii t = q.front();
        q.pop();

        for(int i = 0; i < 4; i ++ ){
            int a = t.x + dx[i],b = t.y + dy[i];
            if(a < 0 || a > n - 1 || b < 0 || b > n - 1) continue;
            if(pre[a][b].x != -1 || g[a][b] != 0) continue;
            pre[a][b] = t;
            q.push(mk(a,b));
        }
    }    
}

int main(){
    for(int i = 0; i < n; i ++ )
        for(int j = 0; j < n; j ++ )
            cin >> g[i][j];
    bfs(n - 1,n - 1);    
    pii end(0,0);

    while(true){
        printf("(%d, %d)\n",end.x,end.y);
        if(end.x == n - 1 && end.y == n - 1) break;
        end = pre[end.x][end.y];
    }    
    return 0;
}