POJ3984 迷宮問題【BFS】

ZMST發表於2019-02-25

題目連結:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<queue>
#include<stack>
#include<vector>
using namespace std;
#define maxn 50
int a[5][5];
int dis[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
int front=0;
int rear=0;
int visit[5][5];
struct node{
    int x,y;
    int pre;
}Node[maxn];
void dfs(int beginX,int beginY,int endX,int endY)
{
    Node[0].x=beginX;
    Node[0].y=beginY;
    Node[0].pre=-1;
    visit[beginX][beginY]=1;
    rear++;
    while (front<rear)
    {
        for(int i=0;i<4;i++)
        {
            int newX=Node[front].x+dis[i][0];
            int newY=Node[front].y+dis[i][1];
            if(newX<0||newX>4||newY<0||newY>4||visit[newX][newY]==1||a[newX][newY]==1)
                continue;
            Node[rear].x=newX;
            Node[rear].y=newY;
            Node[rear].pre=front;
            visit[newX][newY]=1;
            rear++;
            if(newX==endX&&newY==endY)
                return;
        }
        front++;
    }
}
void print(node now)
{
    if(now.pre==-1)
        cout<<"("<<now.x<<", "<<now.y<<")"<<endl;
    else
    {
        print(Node[now.pre]);
        cout<<"("<<now.x<<", "<<now.y<<")"<<endl;
    }
}
int main()
{
    for(int i=0;i<5;i++)
    {
        for(int j=0;j<5;j++)
        {
            cin>>a[i][j];
        }
    }
    dfs(0, 0, 4, 4);
    print(Node[rear-1]);
    return 0;
}

 

相關文章