【复健系列】POJ 3984 迷宫问题 宽度优先搜索

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<vector>
#include<map>
#include<queue>
#include<stack>
using namespace std;

int n,k;
int mmp[10][10];
bool visited[10][10];
int vv[2][4] = {
    {-1,0,1,0},
    {0,-1,0,1}
};
struct pos {
    int x,y,dist;
    pos* prev; // 在到达这个位置时前一步的点
    pos(){}
    pos(int x,int y,int dist,pos* prev):x(x),y(y),dist(dist),prev(prev){}
};

pos* minres = NULL;

void search(){
    queue< pos* >ws;
    pos* t = new pos(0,0,0,NULL);
    ws.push(t);
    while(!ws.empty()) {
        pos* pivot = ws.front(); ws.pop(); 
        int newx, newy;
        if(visited[pivot->y][pivot->x])continue;
        if(pivot->y == 4 && pivot->x == 4) {
            if(minres==NULL || minres->dist > pivot->dist) {
                minres = pivot;
            }
            continue;
        }
        for(int i=0;i<4;i++){
            newx = pivot->x+vv[0][i];
            newy = pivot->y+vv[1][i];
            if(newx>=0&&newx<5&&newy>=0&&newy<5&&(!visited[newy][newx])&&mmp[newy][newx]==0){
                pos* n = new pos(newx,newy,pivot->dist+1,pivot);
                ws.push(n);
            }
        }
        visited[pivot->y][pivot->x] = true;
    }
}

int main(){
    memset(visited,0,sizeof(visited));
    for(int y=0;y<5;y++)for(int x=0;x<5;x++)scanf("%d",&mmp[y][x]);
    search();
    stack< pos* >st;
    while(minres) {
        st.push(minres);
        minres = minres->prev;
    }
    while(!st.empty()) {
        pos* pivot = st.top(); st.pop();
        printf("(%d, %d)\n", pivot->y, pivot->x);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/erikabeats/article/details/81262517