先定义一个游戏类horseChessBoard
和一些属性
private static int X = 6;//表示列
private static int Y = 6;//表示行
private static int[][] chessBoard = new int[Y][X];//二维数组表示棋盘
private static boolean[] visited = new boolean[X * Y];//记录某个位置是否走过
private static boolean finished = false;//记录棋子是否遍历完整个棋盘
这里定义一个6*6的棋盘
我们接下来用一个算法来计算棋子下一步能走的位置,把他放入一个集合中
next方法
//此方法可以获得当前位置可以走的下一步的所有位置
public static ArrayList<Point> next(Point curPoint) {
ArrayList<Point> ps = new ArrayList<>();//创建一个数组存放这些位置
Point p = new Point();
if ((p.x = curPoint.x - 2) >= 0 && (p.y = curPoint.y - 1) >= 0) {
ps.add(new Point(p));
}
if ((p.x = curPoint.x - 1) >= 0 && (p.y = curPoint.y - 2) >= 0) {
ps.add(new Point(p));
}
if ((p.x = curPoint.x + 1) < X && (p.y = curPoint.y - 2) >= 0) {
ps.add(new Point(p));
}
if ((p.x = curPoint.x + 2) < X && (p.y = curPoint.y - 1) >= 0) {
ps.add(new Point(p));
}
if ((p.x = curPoint.x + 2) < X && (p.y = curPoint.y + 1) < Y) {
ps.add(new Point(p));
}
if ((p.x = curPoint.x + 1) < X && (p.y = curPoint.y + 2) < Y) {
ps.add(new Point(p));
}
if ((p.x = curPoint.x - 1) >= 0 && (p.y = curPoint.y + 2) < Y) {
ps.add(new Point(p));
}
if ((p.x = curPoint.x - 2) >= 0 && (p.y = curPoint.y + 1) < Y) {
ps.add(new Point(p));
}
return ps;
}
这里函数返回值为一个ArrayList泛型数组,存放的是Point类
这里用Point对象来表示坐标
这8个if是判断棋子当前坐标能否到下一个坐标,如果能,创建一个新的Point对象加入数组中,这个新的对象的坐标是判断成功的值
现在我们开始整个程序最重要的部分,算法实现
traversal方法
//遍历棋盘
public static void traversal(int[][] chessBoard,int row,int col,int step){
chessBoard[row][col] = step;
visited[row*X+col]=true;
ArrayList<Point> ps= next(new Point(col,row));
while (!ps.isEmpty()){
Point p=ps.remove(0);
if(!visited[p.y*X+p.x]){
traversal(chessBoard,p.y,p.x,step+1);
}
}
if(step<X*Y && !finished){
chessBoard[row][col]=0;
visited[row*X+col]=false;
}else {
finished=true;
}
}
调用此函数需要几个参数,棋盘,行和列坐标,第几步
我们先将该坐标设置为第几步,然后设置visited为true(已被访问)
利用行列坐标创建一个Point对象,调用next方法
把方法返回值赋给一个数组
现在开始循环,只要数组不为空,就取出一个Point对象(remove方法是根据标号删除数组对应元素,然后返回值为要删除的元素)判断是否已访问,如果没有,递归调用traversal进入下一步
下面的if判断是当步数小于棋盘大小(没有走过所有点)或者finished(没有完成),就设置该点为零,表示此路不通,如果不是那说明找到路了