马踏棋盘算法介绍和游戏演示
马踏棋盘算法也被称为骑士周游问题将马随机放在国际象棋的8×8棋盘Board[0~7][0~7]的某个方格中,马按走棋规则(马走日字)进行移动。要求每个方格只进入一次,走遍棋盘上全部64个方格游戏演示: http://www.4399.com/flash/146267_2.htm
马踏棋盘游戏代码分析
马踏棋盘问题(骑士周游问题)实际上是图的深度优先搜索(DFS)的应用。如果使用回溯(就是深度优先搜索)来解决,假如马儿踏了53个点,如图:走到了第53个,坐标(1,0),发现已经走到尽头,没办法,那就只能回退了,查看其他的路径,就在棋盘上不停的回溯…… ,思路分析+代码实现分析第一种方式的问题,并使用贪心算法(greedyalgorithm)进行优化。解决马踏棋盘问题.使用前面的游戏来验证算法是否正确。
图解
代码实现
package horse
;
import java
.awt
.*
;
import java
.util
.ArrayList
;
import java
.util
.Comparator
;
public class HorseChessBoard {
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
= 1;
int column
= 1;
int[][] chessboard
= new int[X
][Y
];
visited
= new boolean[X
* Y
];
long start
= System
.currentTimeMillis();
traversalChessBoard(chessboard
, row
- 1, column
- 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();
}
}
public static void traversalChessBoard(int[][] chessboard
, int row
, int column
, int step
) {
chessboard
[row
][column
] = step
;
visited
[row
* X
+ column
] = true;
ArrayList
<Point> ps
= next(new Point(column
, row
));
sort(ps
);
while (!ps
.isEmpty()) {
Point p
= ps
.remove(0);
if (!visited
[p
.y
* X
+ p
.x
]) {
traversalChessBoard(chessboard
, p
.y
, p
.x
, step
+ 1);
}
}
if (step
< X
* Y
&& !finished
) {
chessboard
[row
][column
] = 0;
visited
[row
* X
+ column
] = false;
} else {
finished
= true;
}
}
public static ArrayList
<Point> next(Point curPoint
) {
ArrayList
<Point> ps
= new ArrayList<>();
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
<Point> ps
) {
ps
.sort(new Comparator<Point>() {
@Override
public int compare(Point o1
, Point o2
) {
return Integer
.compare(next(o1
).size(), next(o2
).size());
}
});
}
}