天天看點

迷宮問題-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