zoj - 1091 - Knight Moves(直接查找法)

#include <iostream>
#include <string>
using namespace std;
int main()
{
    int f[8][8] ={{0, 3, 2, 3, 2, 3, 4, 5},     //因为是8*8的方阵,不是很多数,所以枚举了所有的情况,就是从点(0, 0)到(x, y)最少要几步
                  {3, 2, 1, 2, 3, 4, 3, 4},
                  {2, 1, 4, 3, 2, 3, 4, 5},
                  {3, 2, 3, 2, 3, 4, 3, 4},
                  {2, 3, 2, 3, 4, 3, 4, 5},
                  {3, 4, 3, 4, 3, 4, 5, 4},
                  {4, 3, 4, 3, 4, 5, 4, 5},
                  {5, 4, 5, 4, 5, 4, 5, 6}};
    string a, b;
    while(cin>>a>>b)
    {
        if((a == "a1" && b == "b2") || (a == "b2" && b == "a1")     //小心一种特殊情况:边缘情况
        || (a == "h1" && b == "g2") || (a == "g2" && b == "h1")
        || (a == "a8" && b == "b7") || (a == "b7" && b == "a8")
        || (a == "h8" && b == "g7") || (a == "g7" && b == "h8"))
            cout<<"To get from "<<a<<" to "<<b<<" takes "<<4<<" knight moves."<<endl;
        else
        {
            int x = (int)(a[0] - b[0]);     //计算差距,直接输出
            int y = (int)(a[1] - b[1]);
            x = x >=0 ? x : -x;
            y = y >=0 ? y : -y;
            cout<<"To get from "<<a<<" to "<<b<<" takes "<<f[x][y]<<" knight moves."<<endl;
        }
    }
    return 0;
}

因为是8*8的方阵,不是很多数,所以枚举了所有的情况,就是从点(0, 0)到(x, y)最少要几步


你可能感兴趣的:(zoj - 1091 - Knight Moves(直接查找法))