1. 程式人生 > >YTU OJ 3148: 搜尋基礎之迷宮問題

YTU OJ 3148: 搜尋基礎之迷宮問題

3148: 搜尋基礎之迷宮問題

題目描述

定義一個二維陣列: 

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表示可以走的路,只能橫著走或豎著走,不能斜著走,要求程式設計序找出從左上角到右下角的最短路線。   

輸入

一個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

樣例輸出

(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)
#include<iostream>
#include<algorithm>
#include<queue>
#include<cstdio>
#include<cstdlib>
#include<cstring>
using namespace std;
struct NODE
{
    int x;
    int y;
    int pre;
}b[110];
int a[10][10];
int dx[]={0,-1,0,1};
int dy[]={1,0,-1,0};
void out(int t)
{
    int s[100];
    int top=0;
    s[0]=t;
    while(b[s[top]].pre!=-1)
    {
        top++;
        s[top]=b[s[top-1]].pre;
    }
    while(top>=0)
    {
        printf("(%d, %d)\n",b[s[top]].x-1,b[s[top]].y-1);
        top--;
    }
}
void bfs()
{
    int head=0;
    int rear=0;
    while(head<=rear)
    {
        if(b[head].x==5&&b[head].y==5)
        {
            out(head);
            return;
        }
        for(int i=0;i<4;i++)
        {
            int nx=b[head].x+dx[i];
            int ny=b[head].y+dy[i];
            if(nx>0&&nx<=5&&ny>0&&ny<=5&&a[nx][ny]==0)
            {
                a[nx][ny]=1;
                rear++;
                b[rear].x=nx;
                b[rear].y=ny;
                b[rear].pre=head;
            }
        }
        head++;
    }
}
int main()
{
    for(int i=1;i<=5;i++)
    {
        for(int j=1;j<=5;j++)
        {
            scanf("%d",&a[i][j]);
        }
    }
    b[0].x=1;
    b[0].y=1;
    b[0].pre=-1;
    bfs();
    return 0;
}