POJ_1915_Knight Moves

POJ 1915

题意:给定起点位置和目标位置,求以题中所给的移动方式到达目标位置的移动步数。
思路:由于可能性极多,故用bfs搜索找到一条最短路。

#include <iostream>
#include <iomanip>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <set>
#include <map>
#include <list>
#include <stack>
#include <deque>
#include <queue>
#include <vector>
#include <algorithm>
#include <functional>

#define debug(x) cout << "--------------> " << x << endl

using namespace std;

const double PI = acos(-1.0);
const double eps = 1e-10;
const long long INF = 0x7fffffff;
const long long MOD = 1000000007;
const int MAXN = 300 + 7;
int step[MAXN][MAXN];
bool vis[MAXN][MAXN];
int l;
int dx[] = {-1, -2, -2, -1, 1, 2, 2, 1};
int dy[] = {2, 1, -1, -2, -2, -1, 1, 2};

class Point
{
public:
    Point(int a, int b):x(a), y(b){};
    int x, y;
};
bool isValidRoad(int x, int y)
{
    return x>= 0 && x < l && y >= 0 && y < l && !vis[x][y];
}

void BFS(int x, int y)
{
    step[x][y] = 0;
    Point p(x, y);
    queue<Point> q;
    q.push(p);
    vis[x][y] = true;
    while(!q.empty())
    {
        Point P = q.front();
        q.pop();
        for(int i = 0; i < 8; ++i)
        {
            Point PP(P.x + dx[i], P.y + dy[i]);
            if(isValidRoad(PP.x, PP.y))
            {
                step[PP.x][PP.y] = step[P.x][P.y]+1;
                q.push(PP);
                vis[PP.x][PP.y] = true;
            }
        }
    }
}

int main()
{
     int t;
     scanf("%d", &t);
     while(t--)
     {
         int s = 0;
         memset(step, 0, sizeof(step));
         memset(vis, 0, sizeof(vis));
         scanf("%d", &l);
         int initial_X, initial_Y, target_X, target_Y;
         scanf("%d%d%d%d", &initial_X, &initial_Y, &target_X, &target_Y);
         BFS(initial_X, initial_Y);
         printf("%d\n", step[target_X][target_Y]);
     }
     return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值