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