[POJ] 3984 迷宫问题

2 篇文章 0 订阅

题意:给定一个5*5的迷宫,求从左上角到右下角的最短路径。

分析:BFS跑一下最短路,这里学习一下保存输出最短路径的方法。

代码:

#include<stdio.h>  
#include<cstring>  
#include<algorithm>  
#include<iostream>
#include<vector>
#include<set>
#include<string>
#include<sstream>
#include<map>
#include<list>
#include<queue>
using namespace std; 

const int MAX_N = 10 ; 
int Map[MAX_N][MAX_N] ;
struct node{
    int x , y ,s ; 
    node(int x= 0 , int y=0 ,int s=0):x(x),y(y),s(s){}
};
int book[MAX_N][MAX_N];
node p[MAX_N][MAX_N] ;
int Next[4][2]={{0,1},{1,0},{0,-1},{-1,0}};

void print_ans(node u){
    vector<node> nodes ; 
    for(;;){
        nodes.push_back(u);
        if(u.x==0&&u.y==0) break; 
        u = p[u.x][u.y];
    }
    //nodes.push_back(node(0,0,0));
    for(int i = nodes.size()-1;i>=0;i--){
        printf("(%d, %d)\n",nodes[i].x,nodes[i].y);
    }
}

void bfs(){
    queue<node> q ; 
    book[0][0] = 1 ; 
    node s(0,0,0);
    q.push(s);
    while(!q.empty()){
        node n = q.front(); 
        q.pop();
        if(n.x==4&&n.y==4){
            print_ans(n);
            //cout<<n.s<<endl;
            break;
        }
        for(int i = 0 ; i < 4 ; i ++){
            int tx = n.x + Next[i][0];
            int ty = n.y + Next[i][1];
            int ts = n.s + 1 ;
            if(tx<0||tx>4||ty<0||ty>4) continue ; 
            if(book[tx][ty]==0&&Map[tx][ty]==0){
                book[tx][ty]= 1 ;
                node New(tx,ty,ts);
                p[tx][ty] = n; 
                q.push(New);
            }
        }   
    }
    return ; 
}


int main(){
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
    //ios::sync_with_stdio(false);
    memset(book,0,sizeof(book));
    for(int i = 0 ; i < 5 ; i++ ){
        for(int j = 0 ; j < 5 ; j ++)scanf("%d",&Map[i][j]);
    }
    bfs();
    return 0 ;   
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值