poj2243

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值