马的遍历(bfs)

#include"bits/stdc++.h"
#define endl "\n"
using namespace std;
int s[505][505];
bool v[505][505];
int n,m,a,b;
int dir[8][2]={
   
   {-1,-2},{-2,-1},{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2}};
struct node{
    int x,y,step;
};
queue<node>q;
inline void bfs()
{
    q.push({a,b,0});
    v[a][b]= true;
    s[a][b]=0;
    while (!q.empty())
    {
        node ind = q.front();
        q.pop();
        for(int i=0;i<8;i++){
            int xx =ind.x + dir[i][0] , yy = ind.y + dir[i][1];
            if(xx < 1 || yy < 1 || xx > n || yy > m || v[xx][yy]) continue;
            v[xx][yy] = true;
            s[xx][yy] = ind.step + 1;
            q.push({xx,yy,ind.step+1});
        }
    }
}
inline void ss(){
	for(int i=1;i<=n;i++){
		for(int j=1;j<=m;j++){
			printf("%-5d",s[i][j]);
		}
		printf("\n");
	}
}
int main()
{
    ios::sync_with_stdio(false);
	cin >> n >> m >> a >> b;
    memset(s,-1,sizeof s);
    memset(v,0,sizeof v);
    bfs();
	ss();

	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_53013914/article/details/120620610