P1443 马的遍历 四年级小朋友求教
  • 板块P1443 马的遍历
  • 楼主incra
  • 当前回复6
  • 已保存回复6
  • 发布时间2021/8/2 09:55
  • 上次更新2023/11/4 12:15:40
查看原帖
P1443 马的遍历 四年级小朋友求教
463956
incra楼主2021/8/2 09:55
#include <bits/stdc++.h>
using namespace std;
const int N = 310;
struct point {
	int x,y;
	point () {}
	point (int x1,int y1) {
		x = x1;
		y = y1;
	}
};
int n,m,sx,sy;
queue <point> q;
int ans[N][N];
int dx[] = {2,1,-1,-2,-2,-1,1,2};
int dy[] = {1,2,2,1,-1,-2,-2,-1};
int main () {
	memset(ans,0xff,sizeof(ans));
	cin >> n >> m >> sx >> sy;
	point t (sx,sy);
	q.push(t);
	ans[sx][sy] = 0;
	while (!q.empty()) {
		point w = q.front();
		int x = w.x;
		int y = w.y;
		q.pop();
		for(int i = 0;i <= 7;i++) {
			int xx = x+dx[i];
			int yy = y+dy[i];
			int d = ans[x][y];
			if(xx < 1 || xx > n || yy < 1 || yy > n || ans[xx][yy] != -1) {
				continue;
			}
			ans[xx][yy] = d+1;
			point now(xx,yy);
			q.push(now);
		}
	}
	for(int i = 1;i <= n;i++) {
		for(int j = 1;j <= m;j++) {
			printf("%-5d",ans[i][j]);
		}
		printf("\n");
	}
    return 0;
}

答案错误,实在找不到哪里错了,请各位老师帮忙指点一下,不胜感激!

2021/8/2 09:55
加载中...