骑士周游算法:主要就是两个思想深度遍历和回溯,以当前点为目标,算出下一个能走的点的集合,然后以下一个能走的目标,然后算出下下个能走的目标,最后不能走时,看有没有完成,没有完成就回退,这里需要一个辅助数组来进行判断点是否有没有走。
接下来就是算法了
private boolean[] flag;
private int Y = 8;
private int X = 8;
private boolean isComplete = false;
public void traversalChessboard(int[][] chessboard, int row, int column, int step) {
chessboard[row][column] = step;
flag[row * X + column] = ture;
ArrayList<Point> list = getNext(new Point(row, column));
while(!list.isEmpty()) {
int point = list.remove(0);
if(!flag[point.y * X + point.x]) {
traversalChessboard(chessboard, point.y, point.x, step + 1);
}
}
if() {
chessboard[row][column] = 0;
flag[row * X + column] = false;
}else{
isComplete = true;
}
}
public ArrayList<Point> getNext(Point curPoint) {
ArrayList<Point> ps = new ArrayList<Point>();
Point p1 = new Point();
if((p1.x = curPoint.x - 2) >= 0 && (p1.y = curPoint.y -1) >= 0) {
ps.add(new Point(p1));
}
if((p1.x = curPoint.x - 1) >=0 && (p1.y=curPoint.y-2)>=0) {
ps.add(new Point(p1));
}
if ((p1.x = curPoint.x + 1) < X && (p1.y = curPoint.y - 2) >= 0) {
ps.add(new Point(p1));
}
if ((p1.x = curPoint.x + 2) < X && (p1.y = curPoint.y - 1) >= 0) {
ps.add(new Point(p1));
}
if ((p1.x = curPoint.x + 2) < X && (p1.y = curPoint.y + 1) < Y) {
ps.add(new Point(p1));
}
if ((p1.x = curPoint.x + 1) < X && (p1.y = curPoint.y + 2) < Y) {
ps.add(new Point(p1));
}
if ((p1.x = curPoint.x - 1) >= 0 && (p1.y = curPoint.y + 2) < Y) {
ps.add(new Point(p1));
}
if ((p1.x = curPoint.x - 2) >= 0 && (p1.y = curPoint.y + 1) < Y) {
ps.add(new Point(p1));
}
return ps;
}
骑士周游算法到这就算完成了,这里还可以有优化的点,就是我们使用贪心算法,我们每次走下个点能到最少的点,就是我们把以当前点为目标计算它下个可以走的点的集合,然后把集合中的这些点的能走的点的多少进行一个排序,然后选择一个最少的点走,这里我就懒得写了,大家可以自行实现出来。