天天看点

迷宫问题-POJ 3984

迷宫问题

Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 24348 Accepted: 14206

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)

广度优先搜索

代码:

#include<iostream>
#include<stdio.h>
#include<string.h>
#include <stdlib.h>
#include<vector>
#include<queue>
using namespace std;
#define INF 0x3f3f3f3f
int map[5][5];//定义迷宫
int vis[5][5];//定义搜索遍历
int go[4][2]={{0,-1},{-1,0},{1,0},{0,1}};//方向数组,上下左右

typedef struct Node
{
    int x;
    int y;
}Node;
Node e;
queue <Node> q;
void BFS(Node s)//对迷宫进行广度优先搜索
{
    q.push(s);//当前节点入队列
    while(!q.empty())//当队列不为空时
    {
        Node cursor=q.front();
        q.pop();//出队
        if(cursor.x==e.x&&cursor.y==e.y)
        {
            return;
        }
        for(int i=1;i<=4;i++)
        {
            int x=cursor.x+go[i-1][0];//遍历上下左右四个方向
            int y=cursor.y+go[i-1][1];
            if(x>=0&&x<5&&y>=0&&y<5&&!map[x][y]&&!vis[x][y])//未访问
            {
                vis[x][y]=i;//i
                Node temp;
                temp.x=x;
                temp.y=y;
                q.push(temp);
            }
        }
    }
}

void print(    int x,int y)
{
    int prex,prey;
    if(vis[x][y]!=-1)
    {

        prex=x-go[vis[x][y]-1][0];//前驱x坐标
        prey=y-go[vis[x][y]-1][1];//前驱y坐标
        print(prex,prey);
    }
    printf("(%d, %d)\n",x,y);
}

int main()
{
    int i,j;
    for(i=0;i<5;i++)
    {
        for(j=0;j<5;j++)
        {
            scanf("%d",&map[i][j]);
        }
    }
    memset(vis,0,sizeof vis);
    e.x=4;
    e.y=4;
    Node s;
    s.x=0;
    s.y=0;
    vis[s.x][s.y]=-1;
    BFS(s);
    print(e.x,e.y);
    return 0;
}      

转载于:https://www.cnblogs.com/gcter/p/7380336.html