求助,循环跳不出来
查看原帖
求助,循环跳不出来
1076328
YHL_RP楼主2024/12/2 19:54

求求

#include<bits/stdc++.h>
using namespace std;

const int N = 25;
bool vis[N][N];//标记有没有走过
queue<pair<int, int>> ans;
int horseX[12] = {-1, -2, -2, -1, 1, 2, 2, 1, -2, -2, 2, 2};
int horseY[12] = {2, 1, -1, -2, 2, 1, -1, -2, -2, 2, -2, 2};

int BFS(int x, int y) {
	int level = 1;
	int Hx, Hy;
	while (true) {
		int num = ans.size();
		for (int k = 1; k <= num; k++) {
			for (int i = 0; i < 12; i++) {//把十二的地方都遍历一遍
				x = ans.front().first;
				y = ans.front().second;
				ans.pop();
				Hx = x + horseX[i], Hy = y + horseY[i];
				if (Hx == 1 && Hy == 1) {
					return level;//本来是想到1,1位置才结束
				}
				if (Hx >= 1 && Hx <= 20 && Hy >= 1 && Hy <= 20 && !vis[Hx][Hy]) {
					vis[Hx][Hy] = true;//如果走过再走就没意义了
					ans.push({Hx, Hy});
				}
			}
		}
		level++;
	}
}

int main() {
	int Bx, By, Wx, Wy;
	cin >> Bx >> By >> Wx >> Wy;

	ans.push({Bx, By});
	vis[Bx][By] = true;
	
	cout << BFS(Bx, By) << endl;
	
	while(ans.size()) ans.pop();
	memset(vis, false, sizeof(vis));
	vis[Wx][Wy] = true;
	ans.push({Wx, Wy});
	
	cout << BFS(Wx, Wy);
	return 0;
}
2024/12/2 19:54
加载中...