【BFS】一道经典的迷宫模板问题

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

以上是样例

感觉最近的题都和结构体有关系,在结构体里定义变量,然后调用。

#include <cstdio>
#include <string.h>
#include <iostream>
#include <queue>
int mp[6][6];
int vis[6][6];
int n=5;
int d[4][2]={1,0,0,1,-1,0,0,-1};
using namespace std;
int head=0,tail=1;
struct node
{
    int x,y,step;
}way[105];
void fun(int i)
{
    if(way[i].step!=-1)
    {
        fun(way[i].step);
        printf("(%d, %d)\n",way[i].x,way[i].y);
    }
}
void bfs(int x,int y)
{
    way[head].x=x;
    way[head].y=y;
    way[head].step=-1;
    while(head<tail)
    {
        int i;
        for(i=0;i<4;i++)
        {
            x=way[head].x+d[i][0];
            y=way[head].y+d[i][1];
            if(x<0 || x>n-1 || y<0 || y>n-1 || mp[x][y]==1 || vis[x][y]==1)	continue;
            else
            {
                mp [x][y]=1;
                vis[x][y]=1;
                way[tail].x=x;
                way[tail].y=y;
                way[tail].step=head;
                tail++;
            }
            if(x==4 && y==4)
            {
                fun(head);
            }
        }
        head++;
    }
}
int main()
{
    int i,j;
    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
        {
            scanf("%d",&mp[i][j]);
        }
    }
    printf("(0, 0)\n");
    bfs(0,0);
    printf("(4, 4)\n");//不确定最后一个写不写的话先不写,运行一下样例,如果没有打印出来,再写上去
    return 0;
}
    原文作者:BFS
    原文地址: https://blog.csdn.net/IronCarrot/article/details/53396252
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞