90分求助
查看原帖
90分求助
670207
denglinchenAKIOI楼主2024/8/10 23:32
#include<bits/stdc++.h>
using namespace std;
typedef pair<int, int> zb;
int vis[155][155], qx, qy, zx, zy, n, m;
char Map[155][155];
int tx[9] {1, 1, -1, -1, 2, 2, -2, -2}, ty[9] {2, -2, 2, -2, 1, -1, 1, -1};
int bfs() {
	memset (vis, -1, sizeof vis);
	queue<zb>grass;
	grass.push({qx, qy});
	vis[qx][qy] = 0;
	while (grass.empty() == 0) {
		zb top = grass.front();
		int xx = top.first, xy = top.second;
		for (int i = 1; i <= 8; i++) {
			int zyx = xx + tx[i], zyy = xy + ty[i];
			if (zyx <= m && zyx > 0 && zyy <= n && zyy > 0 && vis[zyx][zyy] == -1) {
				if (Map[zyx][zyy] != '*') {
					vis[zyx][zyy] = vis[xx][xy] + 1;
					if (zyx == zx && zyy == zy) return vis[zyx][zyy];
					grass.push({zyx, zyy});	
				}
			}
		}
		grass.pop();
	}
	return -1;
}
int main() {
	cin >> n >> m;
	for (int i = 1; i <= m; i++) {
		scanf("\n");
		for (int j = 1; j <= n; j++) {
			cin >> Map[i][j];
			if (Map[i][j] == 'K') {
				qx = i;
				qy = j;
			}
			if (Map[i][j] == 'H') {
				zx = i;
				zy = j;
			}
		}
	}
	cout << bfs();
	return 0;
}

求助大佬,帮助必关注

2024/8/10 23:32
加载中...