码迷,mamicode.com
首页 > 其他好文 > 详细

poj 3984 迷宫问题

时间:2018-02-04 22:55:12      阅读:317      评论:0      收藏:0      [点我收藏+]

标签:sample   algorithm   printf   ted   target   turn   dfs   scanf   strong   

                        迷宫问题
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 27854   Accepted: 16056

Description

定义一个二维数组: 

int maze[5][5] = {
0, 1, 0, 0, 0,
0, 1, 0, 1, 0,
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 1, 0,
};

它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。

Input

一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。

Output

左上角到右下角的最短路径,格式如样例所示。

Sample Input

0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0

Sample Output

(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)

Source

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int map[6][6];
int ans=0x7f7f7f7f;
int dx[4]={1,-1,0,0};
int dy[4]={0,0,1,-1};
int ansx[40],ansy[40];
int tmpx[40],tmpy[40];
void dfs(int x,int y,int step){
    if(step>ans)    return ;
    if(x==4&&y==4){
        if(step>ans)    return ;
        ans=step; 
        for(int i=1;i<=step;i++){
            ansx[i]=tmpx[i];
            ansy[i]=tmpy[i];
        }
        return ; 
    }
    for(int i=0;i<4;i++){
        int cx=x+dx[i];
        int cy=y+dy[i];
        if(cx>=0&&cx<=4&&cy>=0&&cy<=4&&!map[cx][cy]){
            tmpx[step+1]=cx;
            tmpy[step+1]=cy;
            map[cx][cy]=1;
            dfs(cx,cy,step+1);
            map[cx][cy]=0;
        }
    }
}
int main(){
    for(int i=0;i<5;i++)
        for(int j=0;j<5;j++)
            scanf("%d",&map[i][j]);
    dfs(0,0,0);
    printf("(0, 0)\n");
    for(int i=1;i<=ans;i++)
        cout<<"("<<ansx[i]<<", "<<ansy[i]<<")"<<endl;
}

 

poj 3984 迷宫问题

标签:sample   algorithm   printf   ted   target   turn   dfs   scanf   strong   

原文地址:https://www.cnblogs.com/cangT-Tlan/p/8414119.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!