Knight Moves UVA - 439

其实就是bfs。

#include <iostream>
#include <bits/stdc++.h>
#define maxn 9
using namespace std;
struct Node
{
    int r,c;
    Node(int i,int j):r(i),c(j){}
    Node(){}
};
int maze[maxn][maxn];
int r1,c1,r2,c2;
int dc[8] = {-2,-1,1,2,2,1,-1,-2};
int dr[8] = {1,2,2,1,-1,-2,-2,-1};
bool vis[maxn][maxn];
Node p[maxn][maxn];

bool bound(int r,int c)
{
    return r>=0&&r<8&&c>=0&&c<8;
}


void BFS(Node u)
{
    int r,c;
    queue<Node>q;
    Node w;
    q.push(u);
    vis[u.r][u.c] = 1;
    while(!q.empty())
    {
        Node v = q.front();q.pop();
        if(v.r == r2 && v.c == c2)
        {
            return;
        }
        for(int i = 0;i<8;i++)
        {
            r=v.r+dr[i];
            c=v.c+dc[i];
            if(!vis[r][c]&&bound(r,c))
            {
                vis[r][c] = 1;
                w = Node(r,c);
                p[r][c] = v;
                q.push(w);
            }
        }
    }
}

int main()
{
    string s1,s2;
    Node u;
    int r,c;
    int ans;
    while(cin>>s1&&cin>>s2)
    {
        ans = 0;
        memset(maze,0,sizeof(maze));
        memset(vis,0,sizeof(vis));
        memset(p,0,sizeof(p));
        c1 = s1[0]-'a';r1 = s1[1]-'1';
        c2 = s2[0]-'a';r2 = s2[1]-'1';
        maze[r1][c1] = 1;maze[r2][c2] = 1;
        BFS(Node(r1,c1));
        r = r2;c = c2;
        while(!(r==r1 && c == c1))
        {
            ans++;
            u = p[r][c];
            r = u.r;c = u.c;
        }
        cout<<"To get from "<<s1<<" to "<<s2<<" takes "<<ans<<" knight moves."<<endl;
    }
    return 0;
}
/**
e2 e4
a1 b2
b2 c3
a1 h8
a1 h7
h8 a1
b1 c3
f6 f6
**/

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值