今天学习了用bts广度优先搜索解决走迷宫问题,看了B站上麦克尔的视频对bfs有了一个深刻的影响了。但是里面的队列的用法,暂时属于我未学习的领域。于是我又在B站上自学了数据结构里的栈和队列的概念和用法。简而言之,队列就是相于排队买东西,先排队的先入列然后后面的接上来,在队尾入列的同时作为先进入的队头就出去了。然后这个过程循环往复。
#include<bits/stdc++.h>
using namespace std;
int a[100][100], v[100][100];
struct point
{
int x;
int y;
int step;
};
queue<point> r;
int dx[4] = { 0,1,0,-1 };
int dy[4] = { 1,0,-1,0 };
int main()
{
int n, m;
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
scanf("%d", &a[i][j]);
scanf("%d%d%d%d", &startx, &starty, &p, &q);
//bfs
point start;
start.x = startx;
start.y = starty;
start.step = 0;
r.push(start);//将起点入队
v[startx][starty] = 1;
while (r.empty())
{
int x = r.front().x, y = r.front().y;
if (x == p && y == q)
{
printf("%d", r.front().step);
break;
}
for (int k = 0; k <= 3; k++)
{
int tx, ty;
tx = x + dx[k];
ty = x + dy[k];
if (a[tx][ty] == 1 && v[tx][ty] == 0)
{
point temp;
temp.x = tx;
temp.step = r.front().step + 1;
r.push(temp);
v[tx][ty] = 1;
}
}
r.pop();
}
if (flag == 0)
printf("no answear");
}
这是用bfs解决迷宫问题的代码,我边学视频边写下了这个代码。