OJ题目:click here ~~
题目分析:骑士跳,就是象棋里面的马走“日”。找最短路径,bfs。
AC_CODE
const int inf = 1000000000;
int grid[10][10];
int startx , starty, endx , endy;
int dir[8][2]= {{2,1},{2,-1},{-2,-1},{-2,1},{1,2},{1,-2},{-1,-2},{-1,2}};
int dp[10][10];
struct Node
{
int x;
int y;
int step;
Node(){}
Node(int i,int j,int k):x(i),y(j),step(k){}
friend bool operator< (const Node &A , const Node &B)
{
return A.step > B.step;
}
};
bool cango(int x , int y)
{
return 1 <= x && x <= 8 && 1 <= y && y <= 8;
}
int bfs(Node start)
{
priority_queue<Node> que;
que.push(start);
while(!que.empty())
{
Node now = que.top();
que.pop();
int x = now.x;
int y = now.y;
int t = now.step;
if(x == endx && y == endy) return t;
for(int i = 0;i < 8;i++)
{
int nx = x + dir[i][0];
int ny = y + dir[i][1];
if(!cango(nx , ny)) continue;
if(dp[nx][ny] > t + 1)
{
dp[nx][ny] = t + 1;
que.push(Node(nx , ny , t + 1));
}
}
}
}
int main()
{
//freopen("in.txt","r",stdin);
string s1 , s2;
while(cin >> s1 >> s2)
{
starty = s1[0] - 'a' + 1;
startx = s1[1] - '1' + 1;
endy = s2[0] - 'a' + 1;
endx = s2[1] - '1' + 1;
Node start = Node(startx, starty, 0);
for(int i = 1;i <= 8;i++)
for(int j = 1;j <= 8;j++)
dp[i][j] = inf;
dp[startx][starty] = 0;
int n = bfs(start);
cout << "To get from " << s1 << " to " << s2 << " takes " << n << " knight moves." << endl;
}
return 0;
}