P1443 Horse traversal (BFS)

Title description

Insert picture description here

Code

#include<bits/stdc++.h> 
typedef long long ll;
using namespace std;
const int maxn = 500;
int n,m,sx,sy,vis[maxn][maxn],ans[maxn][maxn];
int fx[16]={
    
    2,-2,2,-2,-1,1,-1,1},fy[16]={
    
    1,1,-1,-1,2,2,-2,-2};//方向
void bfs(){
    
    
	queue<pair<int,int> >q;
	//初始节点的初始化 
	q.push(make_pair(sx,sy));
	vis[sx][sy] = 1;
	ans[sx][sy] = 0;
	while(!q.empty()){
    
    
		//取出队首节点 
		int xx = q.front().first,yy = q.front().second;
		q.pop();
		for(int i = 0;i< 8;i++){
    
    
			//循环每个方向 
			int dx = xx + fx[i];
			int dy = yy + fy[i];
			if(dx <1 || dx > n || dy < 1|| dy > m || vis[dx][dy] == 1)
				continue;
			vis[dx][dy] = 1;
			q.push(make_pair(dx,dy));
			ans[dx][dy] = ans[xx][yy] + 1;
		}
	}
}
int main(){
    
    
	//freopen("a.txt","r",stdin); 
	memset(ans,-1,sizeof ans);
	cin>>n>>m>>sx>>sy;
	bfs();
	for(int i =1;i<=n;i++){
    
    
		for(int j = 1;j<=m;j++){
    
    
			printf("%-5d",ans[i][j]);
		}
		cout<<endl;
	}
	return 0;
} 

Key points:

make_pair(): Initialization of the pair
printf Default right alignment: printf("%5d",a), left alignment plus minus sign: printf("%-5d",a);

Guess you like

Origin blog.csdn.net/m0_45210226/article/details/108291388