经典跳马问题。
题意:有一只国际象棋的马, 给出马的起点终点坐标,求出马需要移动的最小次数。
广搜吧,没什么好说的。
#include <iostream>
#include <cmath>
#include <algorithm>
#include <cstdio>
#include <vector>
#include <stack>
#include <queue>
#include <cstring>
#include <ctype.h>
#define MAXN 200
using namespace std;
#define INF 2100000000
int n, m;
int map[MAXN][MAXN];
int cnt[MAXN];
int path[8][2] = {{-2, -1}, {-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}};
bool vis[MAXN*MAXN];
bool islegal(int row, int col)
{
if(row < 0 || row >= 8 || col < 0 || col >= 8 || vis[row*8+col]) return 0;
return 1;
}
void bfs(int sta, int end)
{
queue<int> q;
q.push(sta);
vis[sta] = 1;
while(!q.empty())
{
int fr = q.front();
q.pop();
if(fr == end) return;
for(int i = 0; i < 8; i++)
{
int row = fr/8 + path[i][1];
int col = fr%8 + path[i][0];
if(islegal(row, col))
{
int tt = row*8+col;
vis[tt] = 1;
q.push(tt);
cnt[tt] = cnt[fr] + 1;
}
}
}
}
int main()
{
//freopen("C:/Users/zts/Desktop/in.txt", "r", stdin);
string a, b;
while(cin >> a >> b)
{
memset(vis, 0, sizeof(vis));
memset(cnt, 0, sizeof(cnt));
int s = (a[0]-'a')+(a[1]-'0'-1)*8;
int e = (b[0]-'a')+(b[1]-'0'-1)*8;
bfs(s, e);
//printf("To get from e2 to e4 takes 2 knight moves.")
cout << "To get from " << a << " to " << b << " takes " << cnt[e] << " knight moves." << endl;
//cout << cnt[e] << endl;
}
return 0;
}