题目链接:Knight Moves - UVA 439 - Virtual Judge (vjudge.net)
题目其实不难,但是我觉得这道题不严谨,其因有三:
1.为何只遍历一次就能找到最小的步数?我看有的大佬题解上说是最先遍历出来的就是最小的,但是我觉得可能会有特殊情况,比如一开始就选了最长的路线
2.为何要把判断棋盘上一个点是否已经走过了并且把他作为判断依据,实测了一波发现删除这个判断条件依然能AC,(寄,水题无疑了~~~~)
不过这道题还是有很多思路是值得我们借鉴的,比如用一个类对象来表示当前到达的点的状态(包括坐标和经过的步数),还有通过建队列,并且将正在进行的点进行出队入队操作,来记录当前操作的上一步操作的状态,并且将队列为空设为到达终点的终止条件,简直是妙极了!
AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <map>
#include <sstream>
#include <cmath>
#include <queue>
#define maxm 200+10
using namespace std;
int dx[8]= {-2,2,-1,1,-2,2,-1,1};
int dy[8]= {-1,-1,-2,-2,1,1,2,2};
//定义一个类,用于存储某一个时刻的坐标和此时的步数
class p
{
public:
int x,y,d;
p(int xx,int yy,int dd=0):x(xx),y(yy),d(dd) {}
};
string s1,s2;
int a[10][10];
queue<p> t;
bool check(int x,int y)
{
if(x<1||x>8||y<1||y>8)
return false;
return true;
}
int tranfrom(char ch)
{
if(isalpha(ch))
return ch-'a'+1;
if(isdigit(ch))
return ch-'0';
}
int dfs(int x0,int y0,int x1,int y1)
{
while(!t.empty()) t.pop();
t.push(p(x0,y0,0));
memset(a, 0, sizeof(a));
if(x0==x1&&y0==y1)
return 0;
// 通过队列中有无元素来判断是否已经到达终点
while(!t.empty())//证明还未到终点
{
p m=t.front();
t.pop();
for(int i=0; i<8; i++)
{
x0=m.x+dx[i];
y0=m.y+dy[i];
if(!a[x0][y0]&&check(x0,y0))
{
if(x0==x1&&y0==y1)
return m.d+1;
else
{
t.push(p(x0,y0,m.d+1));
a[x0][y0]=1;
}
}
}
}
}
int main()
{
while(cin>>s1>>s2)
{
//cout<<tranfrom(s1[1])<<tranfrom(s1[0])<<tranfrom(s2[1])<<tranfrom(s2[0])<<endl;
cout<<"To get from "<<s1<<" to "<<s2<<" takes "<<dfs(tranfrom(s1[1]),tranfrom(s1[0]),tranfrom(s2[1]),tranfrom(s2[0]))<<" knight moves."<<endl;
}
return 0;
}
一入算法深似海,呕心沥思不能寐