Day3—G
定义一个二维数组:
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)

思路:bfs+queue模拟

代码如下:

#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
int a[6][6];
int vis[6][6];
struct node
{
    int x,y;
}b[6][6];
int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};
void bfs()
{
    queue<node>q;
    node now;
    now.x=0,now.y=0;
    vis[now.x][now.y]=1;
    q.push(now);
    while(!q.empty())
    {
        now=q.front();
        q.pop();
        node next;
        for(int i=0;i<4;i++)
        {
            next.x=now.x+dx[i];
            next.y=now.y+dy[i];
            if(next.x>=0&&next.x<5&&next.y>=0&&next.y<5&&!vis[next.x][next.y]&&a[next.x][next.y]==0)
            {
                vis[next.x][next.y]=1;
                q.push(next);
                b[next.x][next.y]=now;
            }
             if(next.x==4&&next.y==4)
                return;
        }
    }
}
void display(int x,int y)
{
    if(x==0&&y==0)
    {
        cout<<"(0, 0)"<<endl;
    }
    else
    {
        display(b[x][y].x,b[x][y].y);
        cout<<"("<<x<<", "<<y<<")"<<endl;
    }
}
int main()
{
     for(int i=0;i<5;i++)
        for(int j=0;j<5;j++)
            cin>>a[i][j];
        bfs();
        display(4,4);
}