BFS ,WA求助!
查看原帖
BFS ,WA求助!
558686
KinoTsuki楼主2022/10/2 17:02
#include<stdio.h>
#include<queue>
#include<cstring>
using namespace std;

char s[3],e[3];
int abs(int num) {
	return num>0? num:-num;
}
struct node {
	int x,y,stp;
};
bool b[10][10];
queue<node> Q;
const int nx[8]={1,2,2,1,-1,-2,-2,-1};
const int ny[8]={2,1,-1,-2,-2,-1,1,2};
int main() {
	freopen("in.txt","r",stdin);
	A:while(scanf("%s%s",s,e)==2) {
		getchar();
		memset(b,false,sizeof(b));
		while(!Q.empty()) Q.pop();
		int sx,sy,ex,ey;
		sx=s[0]-'a';sy=s[1]-'1';
		ex=e[0]-'a';ey=e[1]-'1';
		if(sx>ex) swap(sx,ex);
		if(sy>ey) swap(sy,ey);
		Q.push({sx,sy,1});b[sx][sy]=true;
	while(!Q.empty()) {
		int x=Q.front().x , y=Q.front().y , stp=Q.front().stp;Q.pop();
		if(x==ex&&y==ey) {
			printf("To get from %s to %s takes %d knight moves.\n",s,e,stp-1);
			goto A;
		}
		for(int pos=0;pos<8;pos++) {
			int tx=x+nx[pos] , ty=y+ny[pos];
			if(tx<0||ty<0||tx>=8||ty>=8||b[tx][ty]) continue;
			Q.push({tx,ty,stp+1});
			b[tx][ty]=true;
		}
	}
	}
}
2022/10/2 17:02
加载中...