poj2243

Knight Moves
这个题是广度优先搜索。做题时首先把数据以恰当的形式存储以便后续操作。本题的核心步骤是,利用队列,由起始状态,依次对步骤进行后续查找,chess1进行检验是否重复操作,chess2状态转移方程,最后在最终位置找到。所有的步骤找到,由于避免了重复,所以复杂度并不高。
#include 
#include 
#include 
using namespace std;

int chess1[9][9],chess2[9][9];
char s1[2],s2[2];
int t1[2],t2[2];

int main()
{
    int t3[8][2]={{2,-1},{2,1},{-2,-1},{-2,1},{1,-2},{-1,-2},{1,2},{-1,2}};
    while(cin >> s1 >> s2)
    {
        memset(chess1,0,sizeof(chess1));
        memset(chess2,0,sizeof(chess2));
        t1[0] = s1[0] - 'a' + 1;t1[1] = s1[1] - '0';
        t2[0] = s2[0] - 'a' + 1;t2[1] = s2[1] - '0';
        queue q;
        q.push(t1[0]);q.push(t1[1]);
        while(!q.empty())
        {
            int x1,y1,tx,ty;
            x1 = q.front();q.pop();y1 = q.front();q.pop();
            chess1[x1][y1] = 1;
            if(x1 == t2[0] && y1 == t2[1])
            break;
            for(int i = 0;i < 8;i = i + 1)
            {
                tx = x1 + t3[i][0];ty = y1 + t3[i][1];
                if(chess1[tx][ty] == 0 && tx >= 1 && tx <= 8&& ty >= 1 && ty <= 8)
                {
                    q.push(tx);q.push(ty);
                    chess1[tx][ty] = 1;
                    chess2[tx][ty] = chess2[x1][y1] + 1;
                }

            }
        }
        cout << "To get from " << s1[0] << s1[1] <<" to " << s2[0] << s2[1] << " takes " << chess2[t2[0]][t2[1]] << " knight moves." << endl;
    }
    return 0;
}


你可能感兴趣的:(poj2243)