为什么一直输出0
  • 板块P1443 马的遍历
  • 楼主zjh2008
  • 当前回复0
  • 已保存回复1
  • 发布时间2023/12/16 19:24
  • 上次更新2023/12/16 21:14:13
查看原帖
为什么一直输出0
778793
zjh2008楼主2023/12/16 19:24
#include<bits/stdc++.h>
using namespace std;
int dx[8] = {-2, -1, 1, 2, 2, 1, -1, -2};
int dy[8] = {-1, -2, -2, -1, 1, 2, 2, 1};
int n, m, x, y, tail, head, flag;
int vis[51][51], mp[51][51];
struct node {
	int x, y, step;
};
node que[2502];
void bfs(int ex, int ey) {
	que[tail].x = 1;
	que[tail].y = 1;
	que[tail].step = 0;
	tail++;
	vis[1][1] = 1;
	while (head < tail) {
		for (int i = 0; i < 8; i++) {
			int nx = que[head].x + dx[i];
			int ny = que[head].x + dy[i];
			if (nx >= 1 && nx <= n && ny >= 1 && ny <= m) {
				if (vis[nx][ny] == 1) {
					que[tail].x = nx;
					que[tail].y = ny;
					que[tail].step = que[head].step + 1;
					tail++;
					vis[nx][ny] = 1;
				}
			}
			if (nx == ex && ny == ey) {
				flag = 1;
				break;
			}
			if (que[tail - 1].step > max(n, m)) {
				flag = 1;
				que[tail - 1].step = -1;
				break;
			}
		}
		if (flag) {
			break;
		}
		head++;
	}
}
int main() {
	cin >> n >> m >> x >> y;
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) {
			memset(que, 0, sizeof(que));
			memset(vis, 0, sizeof(vis));
			//tail = head = 0;
			if (i == x && j == y) {
				mp[i][j] = 0;
			} else {
				bfs(i, j);
				mp[i][j] = que[tail - 1].step;
			}
		}
	}
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) {
			cout << mp[i][j] << ' ';
		}
		cout << endl;
	}
	return 0;
}

2023/12/16 19:24
加载中...