POJ 2243 Knight Moves (BFS入门)

17 篇文章 0 订阅

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;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值