程序设计思维 week2 作业A-Maze

题目

东东有一张地图,想通过地图找到妹纸。地图显示,0表示可以走,1表示不可以走,左上角是入口,右下角是妹纸,这两个位置保证为0。既然已经知道了地图,那么东东找到妹纸就不难了,请你编一个程序,写出东东找到妹纸的最短路线。

Input

输入是一个5 × 5的二维数组,仅由0、1两数字组成,表示法阵地图。

Output

输出若干行,表示从左上角到右下角的最短路径依次经过的坐标,格式如样例所示。数据保证有唯一解。

Sample Input

0 1 0 0 0
0 1 0 1 0
0 1 0 1 0
0 0 0 1 0
0 1 0 1 0

Sample Output

(0, 0)
(1, 0)
(2, 0)
(3, 0)
(3, 1)
(3, 2)
(2, 2)
(1, 2)
(0, 2)
(0, 3)
(0, 4)
(1, 4)
(2, 4)
(3, 4)
(4, 4)

思路

迷宫问题首先给输入的迷宫加一圈墙。
采用bfs,同时加入一个二维数组Parent用于记录路径,Parent[i][j]=p即在路径中点(i,j)经由点p得来。
在main()中,由于Parent记录的是路径中每个点的父节点,故将起点与终点交换反向遍历,则利用Parent输出的路径为起点指向终点(也可正向遍历递归输出,类似week2 作业B)。

代码

#include <iostream>
#include <queue>
#include <string>
using namespace std;

struct Point{
    int x,y;
    Point(){};
    Point(int _x,int _y){
        x=_x;
        y=_y;
    }
};

const int maxn=7;//若不使用const,则Variable length array declaration not allowed at file scope
int graph[maxn][maxn];
bool vis[maxn][maxn];//记录是否到达过
Point parent[maxn][maxn];//记录路径
int dx[]={-1,1,0,0};
int dy[]={0,0,-1,1};

void bfs(Point a,Point b){
    queue<Point> q;
    q.push(a);
    parent[a.x][a.y]=a;
    while (!q.empty()) {
        Point now=q.front();
        vis[now.x][now.y]=true;
        q.pop();
        if(now.x==b.x&&now.y==b.y)//走到终点则结束
            return;
        for(int i=0;i<4;i++){
            int x=now.x+dx[i];
            int y=now.y+dy[i];
            if(1<=x&&(x<maxn-1)&&1<=y&&(y<maxn-1)&&(!vis[x][y])&&graph[x][y]==0){//合法性
                parent[x][y]=now;
                q.push(Point(x,y));
            }
        }
    }
}

int main() {
    for(int i=0;i<maxn;i++){
        graph[0][i]=1;
        graph[6][i]=1;
        graph[i][0]=1;
        graph[i][6]=1;
    }
    memset(vis, false, sizeof(vis));
    for(int i=1;i<maxn-1;i++){
        for(int j=1;j<maxn-1;j++){
            cin>>graph[i][j];
        }
    }
    Point a(1,1),b(maxn-2,maxn-2);
    bfs(b,a);
    Point now(1,1);
    while (!(now.x==maxn-2&&now.y==maxn-2)) {
        cout<<"("<<now.x-1<<", "<<now.y-1<<")"<<endl;
        now=parent[now.x][now.y];
    }
    cout<<"("<<maxn-2<<", "<<maxn-2<<")"<<endl;
    return 0;
}

题目链接

发布了9 篇原创文章 · 获赞 2 · 访问量 149

猜你喜欢

转载自blog.csdn.net/weixin_43805228/article/details/104626735