马踏棋盘
马踏棋盘问题
回溯算法
回溯算法实际上一个类似枚举的搜索尝试过程,主要是在搜索尝试过程中寻找问题的解,当发现已不满足求解条件时,就“回溯”返回,尝试别的路径。
回溯法是一种选优搜索法,按选优条件向前搜索,以达到目标。但当探索到某一步时,发现原先选择并不优或达不到目标,就退回一步重新选择,这种走不通就退回再走的技术为回溯法,而满足回溯条件的某个状态的点称为“回溯点”。
问题基本介绍
1、马踏棋盘算法也被称为骑士周游问题
2、将马随机放在国际象棋的8×8棋盘Board[0~7]的某个方格中,马按走棋规则(马走日字)进行移动。要求每个方格只进入一次,走遍棋盘上全部64个方格
public class HouseChess {
private static int X;
private static int Y;
private static boolean visited[];
private static boolean finished;
public static void main(String[] args) {
X = 8;
Y = 8;
int row = 0; // 马初始行位置
int column = 0; // 马初始列位置
int[][] chessboard = new int[X][Y];
visited = new boolean[X*Y];
traversalChessboard(chessboard,row,column,1);
for (int[] rows:chessboard){
for (int step:rows){
System.out.print(step+"\t");
}
System.out.println();
}
}
/**
* 骑士周游问题算法
* @param chessboard 棋盘
* @param row 马所在行位置
* @param column 马所在列位置
* @param step 第几步
*/
public static void traversalChessboard(int[][] chessboard, int row, int column, int step) {
chessboard[row][column] = step;
//row = 4 X = 8 column = 4 = 4 * 8 + 4 = 36
visited[row * X + column] = true; // 标记该位置已经访问
// 获取当前位置可以走的下一个步的集合
ArrayList ps = next(new Point(column, row));
// 加入贪心算法优化,对ps进行排序,进行非递减排序
sort(ps);
//遍历 ps
while(!ps.isEmpty()) {
Point p = ps.remove(0);// 取出下一个可以走的位置
// 判断该点是否已经访问过
if(!visited[p.y * X + p.x]) {// 未走通
traversalChessboard(chessboard, p.y, p.x, step + 1);
}
}
// 判断马儿是否完成
// 如果没有完成,则棋盘置0
// 说明: step < X * Y 有两种清空
// 1. 棋盘到目前位置,没有走完
// 2. 棋盘回溯
if(step < X * Y && !finished ) {
chessboard[row][column] = 0;
visited[row * X + column] = false;
} else {
finished = true;
}
}
public static ArrayList next(Point curPoint) {
// 创建一个ArrayList
ArrayList 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;
}
//贪心算法
// 非递减排序
public static void sort(ArrayList ps) {
ps.sort(new Comparator() {
@Override
public int compare(Point o1, Point o2) {
// 获取o1的下一步所有位置个数
int count1 = next(o1).size();
// 获取o2的下一步所有位置个数
int count2 = next(o2).size();
if(count1 < count2) {
return -1;
} else if (count1 == count2) {
return 0;
} else {
return 1;
}
}
});
}
}