骑士的移动(Knight Moves, UVa 439)

本题实际上就是一次BFS,很普通,我这里利用对称性,将a-h视作行,1-8视作列,且a在上,h在下,1在左,7在右,这样符合C语言的数组习惯

#include<iostream>
#include <queue>
#include <string>
using namespace std;
const int maxn = 8+5;
int dir[maxn][maxn]; //初始值设为0,表示还未访问,出发点的值设为1,以后没进一层,相应位置dir值加1,输出最后结果记得减1
queue<int> qx, qy;
int tox[] = {-2,-1,1,2,2,1,-1,-2};
int toy[] = {1,2,2,1,-1,-2,-2,-1};
void go(string s1, string s2)
{
	int x1 = s1[0] - 'a', y1 = s1[1] - '1';
	int x2 = s2[0] - 'a', y2 = s2[1] - '1';
	qx.push(x1); qy.push(y1); dir[x1][y1] = 1;
	while(!qx.empty())  //既然qx,qy同进同出,判断一个就好
	{
		int x = qx.front();qx.pop();
		int y = qy.front();qy.pop();
		if(x == x2 && y == y2) break;
		for(int i = 0; i < 8; i++)
		{
			if (x + tox[i] >= 0 && x + tox[i] <= 7 && y + toy[i] >= 0 && y + toy[i] <= 7 && dir[x + tox[i]][y + toy[i]] == 0)
			{
				dir[ x + tox[i] ][ y + toy[i] ] = dir[x][y] + 1;
				qx.push(x + tox[i]); qy.push(y + toy[i]);
			}
		}
	}
	cout<<"To get from " <<s1 << " to "<< s2<<" takes "<< dir[x2][y2] - 1<< " knight moves."<<endl;
}
int main()
{
	string s1, s2;
	while(cin>>s1>>s2)
	{
		//初始化
		memset(dir, 0, sizeof(dir));
		while (!qx.empty()) qx.pop();
		while(!qy.empty())qy.pop();		
		go(s1, s2);
	}
	
}

    原文作者:骑士周游问题
    原文地址: https://blog.csdn.net/qq_25974431/article/details/74332320
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞