#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
char map[101][101];
int dir[4][2] = { -1,0,1,0,0,-1,0,1 };//某个点的四个方向
bool vist[101][101] = { false };//标记是否已访问
int Xa, Ya, Xb, Yb, N, ans;//记录A,B坐标和步数
struct node {
int x, y;
}Qunue[10000];//利用辅助队列进行广度优先搜索
void establishmap()//输入图
{
scanf("%d", &N);
for (int i = 0; i < N; i++)
{
int j;
for (j = 0; j < N; j++)
{
getchar();
scanf("%c", &map[i][j]);
if (map[i][j] == 'A')
{
Xa = i;
Ya = j;
}
else if (map[i][j] == 'B')
{
Xb = i;
Yb = j;
}
}
map[i][j] = '\0';
}
}
void bfs()
{
int front = 0, rear = 0;
Qunue[rear].x = Xa;//起点入队
Qunue[rear].y = Ya;
vist[Xa][Ya] = 1;//任何位置只要入队都要标记为已访问
rear = (rear + 1) % 10000;//循环队列
while (rear != front)//辅助队列进行广搜
{
int n = front;
int m = rear;//记录某个点四周有多少个点
for (int j = 0; j < m - n; j++)//某个点的四周,走完四周位为一步
{
int pushx = Qunue[front].x;
int pushy = Qunue[front].y;//记录某个出队点的位置坐标
front = (front + 1) % 10000;//对头指针环+1
if (pushx == Xb && pushy == Yb)//找到直接返回
return;
for (int i = 0; i < 4; i++)//遍历四个方向
{
int nextx = pushx + dir[i][0];
int nexty = pushy + dir[i][1];
if (nextx < 0 || nextx >= N || nexty < 0 || nexty >= N)//越界
continue;
if (vist[nextx][nexty])//已被访问
continue;
if (map[nextx][nexty] == map[pushx][pushy])//同种磁场
continue;
Qunue[rear].x = nextx;
Qunue[rear].y = nexty;
vist[nextx][nexty] = 1;//标记为访问
rear = (rear + 1) % 10000; //队尾环比+1
}
}
ans++;//走完一个点的四周,步数加一
}
ans = -1; //队列为空,都还没有在上方返回,则不能到B点
}
int main(int argc, char* argv[])
{
establishmap();//建图
bfs();//广搜
printf("%d", ans);
return 0;
}
标签:南桥,Qunue,int,nexty,穿越,front,nextx,雷区,rear
From: https://blog.csdn.net/m0_73061507/article/details/137471282