迷宫问题 POJ - 3984

定义一个二维数组: 

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)

AC代码(个人觉得记录路径是一个难点)

Select Code

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
//#include <bits/stdc++.h>
using namespace std;
int mp[10][10];
int vis[10][10];
int n = 5;
struct node
{
    int x, y;
    int c;
}s, t, q[100];
int nxt[5][3] = {{0,1},{0,-1},{1,0},{-1,0}};
void yin(int head) //先走到最后然后再通过递归来输出路线
{
    while(q[head].c!=-1)
    {
        yin(q[head].c);
        printf("(%d, %d)\n",q[head].x, q[head].y);
        return;
    }
   printf("(%d, %d)\n",0,0);
}
void bfs(int ii, int jj)
{
    int i;
    memset(vis, 0, sizeof(vis));
    int tail = 0, head = 0;
    s.x = ii, s.y = jj, s.c = -1;
    q[tail++] = s;
    vis[s.x][s.y] = 1;
    while(head<tail)
    {
        s = q[head];
        if(s.x==4&&s.y==4)
        {
            yin(head);
            return;
        }
        for(i = 0;i<4;i++)
        {
            t.x = s.x+nxt[i][0];
            t.y = s.y+nxt[i][1];
            if(t.x>=0&&t.x<n&&t.y>=0&&t.y<n&&mp[t.x][t.y]!=1&&!vis[t.x][t.y])
            {
                vis[t.x][t.y] = 1;
                t.c = head; //记录上一个走过的点
                q[tail++] = t;
            }
        }
        head++;
    }
    return;
}
int main()
{
    int i, j;
    for(i = 0;i<n;i++)
    {
        for(j = 0;j<n;j++)
        {
            scanf("%d",&mp[i][j]);
        }
    }
    bfs(0,0);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41524782/article/details/82011338