http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=91
http://acm.hdu.edu.cn/showproblem.php?pid=1372
BFS是自己写的,DFS是看别人的。
代码:
#include <cstdio>
#include <string>
#include <cstring>
#include <queue>
using namespace std;
const int dx[] = {1, 1, 2, 2, -2, -2, -1, -1};
const int dy[] = {2, -2, 1, -1, 1, -1, 2, -2};
const int N = 10;
char ch1, ch2, ch3, ch4;
int x1, y1, x2, y2;
int visited[N][N]; //used in bfs
int used[N][N]; //used in dfs
bool inside(int x, int y)
{
return (0 <= x && x <= 7 && 0 <= y && y <= 7);
}
void bfs()
{
queue<int> q;
visited[x1][y1] = 1;
q.push(x1);
q.push(y1);
int x, y;
while (!q.empty())
{
x = q.front(), q.pop();
y = q.front(), q.pop();
if (x == x2 && y == y2)
{
printf("To get from %c%c to %c%c takes %d knight moves.\n", ch1, ch2, ch3, ch4, visited[x2][y2]-1);
break;
}
for (int i = 0; i < 8; i++)
{
int tmpx = x + dx[i], tmpy = y + dy[i];
if (inside(tmpx, tmpy) && !visited[tmpx][tmpy])
{
q.push(tmpx);
q.push(tmpy);
visited[tmpx][tmpy] = visited[x][y] + 1;
}
}
}
}
void dfs(int x, int y, int t)
{
if (!inside(x, y) || t >= used[x][y]) //剪枝
return;
used[x][y] = t; //当不越界时,对地图进行松弛,将步数更新为当前最小
for (int i = 0; i < 8; i++)
dfs(x+dx[i], y+dy[i], t+1);
}
int main()
{
//freopen("in", "r", stdin);
while (scanf("%c%c %c%c\n", &ch1, &ch2, &ch3, &ch4) != EOF)
{
x1 = ch1 - 'a', y1 = ch2 - '1';
x2 = ch3 - 'a', y2 = ch4 - '1';
// memset(visited, 0, sizeof(visited));
// bfs();
for (int i = 0; i < 8; i++)
for (int j = 0; j < 8; j++)
used[i][j] = 64;
dfs(x1, y1, 0);
printf("To get from %c%c to %c%c takes %d knight moves.\n", ch1, ch2, ch3, ch4, used[x2][y2]);
}
}