【BFS】Ybt_走迷宫

一个 N ∗ N N*N NN 的地图,求从 ( q x , q y ) (qx,qy) (qx,qy) 走到 ( z x , z y ) (zx,zy) (zx,zy) 需要几步。


标准的BFS。
每个坐标可以用 数组 或是 改成序号用序列,还可以尝试 make_pair 存到序列里。


代码

#include<cstdio>
#include<queue>
#include<cstring>
#include<iostream>
using namespace std;
queue <pair <int, int> > Q; 
int a[1006][1006], S[1006][1006], fx[6] = {
    
    0,1,-1}, fy[6] = {
    
    0,0,0,1,-1};
int n, qx, qy, zx, zy, x, y;
bool check(int xx, int yy){
    
    
	if(a[xx][yy] == 1 || xx < 0 || yy < 0 || xx > n || yy > n) return 0;
	if(S[xx][yy] != -1)
		return 0;
	return 1;
}
int main(){
    
    
	memset(S, -1, sizeof(S));  //存距离
	scanf("%d", &n);
	for(int i = 1; i <= n; ++i)
	  for(int j = 1; j <= n; ++j)
	    scanf("%1d", &a[i][j]);
	scanf("%d%d%d%d", &qx, &qy, &zx, &zy);
	Q.push(make_pair(qx, qy));  //丢入序列
	S[qx][qy] = 0;
	while(!Q.empty()){
    
    
		x = Q.front().first;
		y = Q.front().second;
		Q.pop();
		for(int i = 1; i <= 4; ++i)
		  if(check(x+fx[i], y+fy[i])){
    
      //判断是否可以走
		  	  S[x+fx[i]][y+fy[i]] = S[x][y] + 1;
		  	  Q.push(make_pair(x+fx[i], y+fy[i]));
		  } 
	}
	printf("%d",S[zx][zy]);
} 

猜你喜欢

转载自blog.csdn.net/qq_42937087/article/details/112883859