439 - Knight Moves

来源:互联网 发布:程序员试用期总结 编辑:程序博客网 时间:2024/06/05 22:46

这是一道简单的最短路的问题,由于地图较小,用深度遍历和广度遍历应该都不会超时,此处使用广度遍历作为示范:



#include <iostream>
#include <algorithm>
#include <string>
#include <stack>
#include <queue>
#include <cstring>
#include <cstdio>




using namespace std;




int web[10][10];


void getpos(char* inp, int &x, int &y)
{
    x = inp[0]-'a'+1;
    y = inp[1]-'0';
}


int bfs(pair<int, int> st, pair<int, int> ed)
{
    web[st.first][st.second] = 0;
    queue<pair<int, int> > qe;
    qe.push(st);
    while(!qe.empty())
    {
        pair<int, int> temp=qe.front();
        int stp = web[temp.first][temp.second];
        if(temp == ed)
            return stp;
        ++stp;
        qe.pop();
        for(int i = -2; i <= 2; ++i)
            for(int j = -2; j <= 2; ++j)
            {
                if(i && j && abs(i) != abs(j) && temp.first+i >=1 && temp.first+i <= 8 && temp.second+j >=1 && temp.second+j <= 8)
                {
                    if(!web[temp.first+i][temp.second+j])
                    {
                        //printf("=| %d %d %d %d\n", temp.first+i, temp.first+j, i, j)
                        web[temp.first+i][temp.second+j] = stp;
                        qe.push(make_pair(temp.first+i, temp.second+j));
                        if(make_pair(temp.first+i, temp.second+j) == ed)
                            return stp;
                    }
                }
            }
    }
    return 0;
}


const int inf = 1<<30;


int main()
{
    //InIt
    char st[5], to[5];
    while(~scanf("%s %s", st, to))
    {
        memset(web, 0, sizeof(web));
        int stx, sty, tox, toy;
        getpos(st, stx, sty);
        getpos(to, tox, toy);
       // printf("%d %d %d %d\n", stx, sty, tox, toy);
        printf("To get from %s to %s takes %d knight moves.\n", st, to, bfs(make_pair(stx, sty) ,make_pair(tox, toy)));
    }


    return 0;
}


0 0
原创粉丝点击