BFS最基础题,话说刚开始我还不知道那个Knight怎么走的,后来搜了才发现原来是日字形走法,中间用到queue就先用JAVA写了,保证算法正确性是主要,数据结构次考虑,C实在不方便。。后来想用C重写,写着写着就不想写了。。还是太懒了,先用JAVA将就吧,下次再用C。。
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
while (sc.hasNext())
{
String line = sc.nextLine().trim();
String[] ss = line.split(" ");
int r1 = ss[0].charAt(1) - '1';
int c1 = ss[0].charAt(0) - 'a';
int r2 = ss[1].charAt(1) - '1';
int c2 = ss[1].charAt(0) - 'a';
int move = BFS(r1, c1, r2, c2);
System.out.format("To get from %s to %s takes %d knight moves.\n",
ss[0], ss[1], move);
}
}
static ArrayList<ChessPoint> getAdj(ChessPoint[][] chess, ChessPoint cp)
{
ArrayList<ChessPoint> res = new ArrayList<ChessPoint>();
int r = cp.r;
int c = cp.c;
if (r - 2 > -1 && c - 1 > -1)
res.add(chess[r - 2][c - 1]);
if (r - 1 > -1 && c - 2 > -1)
res.add(chess[r - 1][c - 2]);
if (c + 1 < 8 && r - 2 > -1)
res.add(chess[r - 2][c + 1]);
if (c + 2 < 8 && r - 1 > -1)
res.add(chess[r - 1][c + 2]);
if (r + 1 < 8 && c - 2 > -1)
res.add(chess[r + 1][c - 2]);
if (r + 2 < 8 && c - 1 > -1)
res.add(chess[r + 2][c - 1]);
if (r + 1 < 8 && c + 2 < 8)
res.add(chess[r + 1][c + 2]);
if (r + 2 < 8 && c + 1 < 8)
res.add(chess[r + 2][c + 1]);
return res;
}
static int BFS(int r1, int c1, int r2, int c2)
{
if (r1 == r2 && c1 == c2)
return 0;
else
{
ChessPoint[][] chess = new ChessPoint[8][8];
for (int i = 0; i < 8; i++)
for (int j = 0; j < 8; j++)
{
ChessPoint cp = new ChessPoint();
cp.r = i;
cp.c = j;
cp.reached = false;
cp.distance = Integer.MAX_VALUE;
chess[i][j] = cp;
}
ChessPoint begin = chess[r1][c1];
ChessPoint end = chess[r2][c2];
begin.reached = true;
begin.distance = 0;
LinkedList<ChessPoint> queue = new LinkedList<ChessPoint>();
queue.addLast(begin);
boolean find = false;
int result = 0;
while (!find)
{
ChessPoint now = queue.removeFirst();
ArrayList<ChessPoint> adjs = getAdj(chess, now);
for (ChessPoint cp : adjs)
{
if (!cp.reached)
{
cp.distance = now.distance + 1;
cp.reached = true;
if (cp.r == end.r && cp.c == end.c)
{
find = true;
result = cp.distance;
break;
}
queue.addLast(cp);
}
}
}
return result;
}
}
}
class ChessPoint
{
int r;
int c;
boolean reached;
int distance;
}