韩老师的最后一节课讲述了关于骑士周游问题的算法优化问题,感觉内容相对比较难以理解,因此我这里尝试使用我的理解和通俗理解对该问题进行解释:
步骤和思路分析:
1,创建棋盘chessBoard,是一个二维数组
2,将当前位置设置为已经访问,然后根据当前位置,计算马儿还能走哪些位置,并放入到一个集合中(ArrayList),最多有8个,每走一步就step+1,即记录下步数
3,遍历ArratList中存放的所有位置,看看哪个可以走,如果可以走通就继续,走不通就回溯(使用贪心算法进行优化的部分就是在这里,通过减少回溯次数来减少运行时间)
4,判断马儿是否完成了任务(即有没有走满整棋盘),使用step和应该走的步数比较,如果没有达到数量,则表示没有完成任务,将整个棋盘设置为0
注:马儿走的策略不同,则得到的结果也不一样,效率也不一样
代码分析:
import java.awt.*;
import java.util.ArrayList;
public class HorseChessBoard {
//定义属性
private static int X = 6; //表示col
private static int Y = 6; //表示row
private static int[][] chessBoard = new int[Y][X]; //棋盘
private static boolean[] visited = new boolean[X * Y]; //记录某个位置是否走过
private static boolean finished = false; //记录马是否遍历完棋盘
public static void main(String[] args) {
int row = 5;
int col = 5;
long start = System.currentTimeMillis();
traversalChessBoard(chessBoard, row - 1, col - 1, 1);
long end = System.currentTimeMillis();
System.out.println("遍历耗时=" + (end - start));
//输出当前这个棋盘的情况
for (int[] rows : chessBoard) {
for (int step : rows) {
System.out.print(step + "\t");
}
System.out.println();
}
}
//编写最核心算法,遍历棋盘,如果遍历成功,就把finished设置为true,并且将马走的每步step记录到chessBoard
/**
* 理解:每次选择一条路走到死胡同为止,再一步步回溯,每一次回溯就就会再次增多选择,直到这些选择全部走完,就回到最开始的位置再次开始遍历
**/
public static void traversalChessBoard(int[][] chessBoard, int row, int col, int step) {
//先把step记录到chessBoard
chessBoard[row][col] = step;
//把这个位置设置为已经访问
visited[row * X + col] = true;
//获取当前这个位置可以走的下一个位置有哪些
ArrayList<Point> ps = next(new Point(col, row)); //col - X, row - Y
//遍历
while (!ps.isEmpty()) {
//取出一个位置(点)
Point p = ps.remove(0);
//判断该位置是否走过,如果没有走过,就递归遍历
if (!visited[p.y * X + p.x]) { //