POJ 3984 & [kuangbin带你飞]专题一 简单搜索 K

来源:互联网 发布:涉密网络三员考试 编辑:程序博客网 时间:2024/06/04 08:02

K - 迷宫问题

定义一个二维数组:

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)

#include<iostream>#include<cstring>using namespace std;const int INF=0x3f3f3f3f;int cnt[4][2]={1,0,-1,0,0,1,0,-1};bool book[6][6];int ans[6][6];struct Node {    int x,y;}path[50],temp[50];int cur=INF;void print(){    cout<<"(0, 0)"<<endl;    for(int i=1;i<cur;i++) cout<<"("<<temp[i].x<<", "<<temp[i].y<<")"<<endl;    cout<<"(4, 4)"<<endl;}void dfs(int x,int y,int step) {    if(ans[x][y]==1) return ;    else if(x==4&&y==4) {        if(cur>step) {            cur=step;            for(int i=0;i<=cur;i++)            temp[i]=path[i];        }        return ;    }    for(int i=0;i<4;i++) {        int tx=x+cnt[i][0],ty=y+cnt[i][1];        if(book[tx][ty]==false) {            book[tx][ty]=true;            if(tx>=0&&tx<5&&ty>=0&&ty<5&&ans[tx][ty]!=1) {                path[step].x=x,path[step].y=y;                dfs(tx,ty,step+1);                book[tx][ty]=false;            }        }    }    return ;}int main(){    ios::sync_with_stdio(0);    cin.tie(0);    memset(ans,0,sizeof(ans));    memset(book,false,sizeof(book));    for(int i=0;i<5;i++) {        for(int j=0;j<5;j++) {            cin>>ans[i][j];        }    }    book[0][0]=true;    dfs(0,0,0);    print();    return 0;}
阅读全文
0 0
原创粉丝点击