利用Java解决骑士周游问题
概述
骑士周游问题是将马随机放在国际象棋8x8的棋盘中,马按照走步规则进行走动,要求马只能进入每个方格一次,不能重复走进已走过的方格,并走遍棋盘上所有的64个方格。
解答过程
1、建立一个二维数组模拟棋盘
//建立一个8x8的棋盘
public class chess(){
private static int X = 8;
private static int Y = 8;
private static int[][] chessBoard = new int[X][Y];
public static void mian(String[] args){
//遍历棋盘
for (int i = 0; i < X; i++) {
for (int j = 0; j < Y; j++) {
System.out.print(chessBoard[i][j] + "\t");
}
System.out.println();
}
}
}
8x8的棋盘
2、跟据马的行走规则,如图所示的马所处的位置下一步只能走到1到8位置中的任意一个位置,由这个规律可以判断马的下一步的位置是否可走。
//当前的位置可以走下一步的位置
public static ArrayList<Point> nextLocation(Point currentPoint) {
//建立一个列表存放可以走的位置
ArrayList<Point> pointList = new ArrayList<Point>();
Point p = new Point();
//判断1位置是否可走
if ((p.x = currentPoint.x - 1) >= 0 && (p.y = currentPoint.y - 2) >= 0) {
pointList.add(new Point(p));
}
//判断2位置是否可走
if ((p.x = currentPoint.x + 1