poj 3984 迷宫问题

    xiaoxiao2021-12-14  21

    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)

    思路 递归打印路径

    /************************************************************************* > File Name: poj3984.cpp > Author:ukiy > Mail: > Created Time: 20161203日 星期六 203257************************************************************************/ #include<iostream> #include<cstdio> #include<algorithm> #include<cmath> #include<cstdlib> #include<climits> #include<string> #include<cstring> #include<vector> #include<set> #include<list> #include<map> #include<queue> int dire[4][2]={ {0,1},{1,0},{0,-1},{-1,0} }; int dire2[8][2]={{-1,-1},{-1,0},{-1,1},{ 0,-1},{ 0,1},{ 1,-1},{ 1,0},{ 1,1}}; #define rep(i,a,b) for(int i=(a);i<=(b);(i++)) #define inf 0x3f3f3f #define ll long long #define pi acos(-1) int dire3[6][3]={ {0,0,1},{0,1,0},{1,0,0},{0,0,-1},{0,-1,0},{-1,0,0} }; using namespace std; const int maxn=5; int a[maxn][maxn];//标记(x,y)是否遍历过 struct node{ int x,y,pre; //pre是在打印最短路径时标记当前node 上一个在q数组中的下标 }q[maxn]; void Print(int i){//递归打印路径 if(q[i].pre!=-1){ Print(q[i].pre); printf("(%d, %d)\n",q[i].x,q[i].y); } } void bfs(int cx,int cy){ int front=0,rear=1,px,py; q[front].x=cx; q[front].y=cy; q[front].pre=-1; while(front < rear){ rep(i,0,3){ px=q[front].x+dire[i][0]; py=q[front].y+dire[i][1]; if(px<0||px>4||py<0||py>4||a[px][py]) //剪枝 continue; else{ a[px][py]=1; q[rear].x=px; q[rear].y=py; q[rear].pre=front; rear++; } if(px==4&&py==4) Print(front); } front++; } } int main() { std::ios::sync_with_stdio(false); #ifndef OnlineJudge //freopen("in.txt","r",stdin); //freopen("out.txt","w",stdout); #endif int i,j,k,m,n; memset(a,0,sizeof(a)); rep(i,0,4){ rep(j,0,4){ cin>>a[i][j]; } } printf("(0, 0)\n"); bfs(0,0); printf("(4, 4)\n"); return 0; }
    转载请注明原文地址: https://ju.6miu.com/read-971558.html

    最新回复(0)