Knight Moves UVA - 439 BFS最短路径长度

题目链接

题目大意:

给起点和终点,求出最短路径长度。

分析:

是UVA1599题目的一半,只从终点开始BFS,用map记录每个点到终点的距离(不要忘记标记)。

map中起点键对应的值即为最短距离。

#include <bits/stdc++.h>
using namespace std;
string beg, ed;
int dir[10][10] = {{1,2},{1,-2},{-1,2},{-1,-2},{2,1},{2,-1},{-2,1},{-2,-1}};
map<string,int> vis;
map<string,int> dis;
int cnt;
bool feasible(char ch1, char ch2) {
    return ch1 >= 'a' && ch1<='h' && ch2>='1' && ch2<='8';
}

void bfs_re() {
    queue<string> queue1;
    queue1.push(ed);
    dis[ed] = 0;
    vis[ed] = 1;
    while(!queue1.empty()) {
        string u = queue1.front(); queue1.pop();
        for(int i = 0; i < 8; i++) {
            char ch1 = (char)(u[0]+dir[i][0]);
            char ch2 = (char)(u[1]+dir[i][1]);
            if(feasible(ch1,ch2)) {
                char vv[5];
                vv[0] = ch1, vv[1] = ch2, vv[2] = 0;
                string v = vv;
                if(!vis.count(v)) {
                    vis[v] = 1;
                    dis[v] = dis[u] + 1;
                    queue1.push(v);
                }
            }
        }
    }
}

int main() {
    freopen("i.txt","r",stdin);
    freopen("o.txt","w",stdout);
    while(cin >> beg >> ed) {
        cnt = 0;
        dis.clear(); vis.clear();
        bfs_re();
        cout << "To get from "<< beg <<" to " << ed << " takes " << dis[beg] << " knight moves." << endl;
    }
}

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值