迷宫问题(bfs+路径打印)

菜鸟的手笔,有写的不好但好歹能ac。(滑稽.jpg)

#include <iostream>
#include <queue>
using namespace std;
int A[10][10];
int B[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
bool vis[10][10];
struct node{
    int x,y;
    node* pre;
};
queue<node*> t;
void bianli(node* T);
void dfs(int a,int b){
    node* head=new node;
    head->x=a; head->y=b; head->pre=NULL;
    t.push(head);
    vis[head->x][head->y]=true;
    while(!t.empty()){
        node* l=t.front(); t.pop();
        for(int i=0;i<4;i++){
            node* temp=new node;
            temp->x=l->x+B[i][0];
            temp->y=l->y+B[i][1]; temp->pre=l;
            if(temp->x==4&&temp->y==4){
                bianli(temp); break;
            }
            if(temp->x>=0&&temp->x<5&&temp->y>=0&&temp->y<5&&A[temp->x][temp->y]!=1&&!vis[temp->x][temp->y]){
                vis[temp->x][temp->y]=true;
                t.push(temp);
            }
        }
    }
}
void bianli(node* T){//类似二叉树中序遍历
    if(T->pre==NULL){
        cout<<"(0, 0)"<<endl; return ;
    }
    bianli(T->pre);
    cout<<"("<<T->x<<", "<<T->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);
}
```[题目出处](http://poj.org/problem?id=3984)

发布了24 篇原创文章 · 获赞 2 · 访问量 473

猜你喜欢

转载自blog.csdn.net/chineseherofeng/article/details/104671237