骑士周游问题
马踏棋盘算法
import java.awt.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class HorseChessBoard {
private static int X;//棋盘的列数
private static int Y;//棋盘的行数
private static boolean isFinished = false;//记录是否完成比赛
public static void main(String[] args) {
X = 6;
Y = 6;
//起始位置
int row = 1;//初始的行,是纵轴Y
int col = 1;//初始的列,是横轴X
int[][] chessBoard = new int[Y][X];//原始棋盘,注意访问顺序与X,Y轴不同之处
long start = System.currentTimeMillis();
backTracing(chessBoard, row, col, 1);
long end = System.currentTimeMillis();
System.out.println(end - start + "ms");
for (int[] rows : chessBoard) {
System.out.println(Arrays.toString(rows));
}
}
private static void backTracing(int[][] chessBoard, int row, int col, int step) {
chessBoard[row][col] = step;//当前的位置标记为第step步
List<Point> points = getNext(row, col);
points.sort(new Comparator<Point>() {
@Override
public int compare(Point o1, Point o2) {
return getNext(o1.y,o1.x).size() - getNext(o2.y, o2.x).size();
}
});
while(points.size() > 0) {
Point point = points.remove(0);
if(chessBoard[point.y][point.x] == 0){
backTracing(chessBoard, point.y, point.x, step + 1);
}
}
//先判断是否完成比赛
if(step == X * Y || isFinished) {
isFinished = true;
} else {
//回溯
chessBoard[row][col] = 0;
}
}
private static List<Point> getNext(int row, int col) {
List<Point> points = new ArrayList<>();
int x = 0, y = 0;
if((y = row - 1) >= 0 && (x = col - 2) >= 0) {
points.add(new Point(x, y));
}
if((y = row - 2) >= 0 && (x = col - 1) >= 0) {
points.add(new Point(x, y));
}
if((y = row - 2) >= 0 && (x = col + 1) < X) {
points.add(new Point(x, y));
}
if((y = row - 1) >= 0 && (x = col + 2) < X) {
points.add(new Point(x, y));
}
if((y = row + 1) < Y && (x = col + 2) < X) {
points.add(new Point(x, y));
}
if((y = row + 2) < Y && (x = col + 1) < X) {
points.add(new Point(x, y));
}
if((y = row + 2) < Y && (x = col - 1) >= 0) {
points.add(new Point(x, y));
}
if((y = row + 1) < Y && (x = col - 2) >= 0) {
points.add(new Point(x, y));
}
return points;
}
}