骑士周游问题求解
完成这个算法,需要预先定义如下几个变量:棋盘的行列数,棋盘是否已被访问过,是否所有位置都被访问。
首先需要设置一个算法确定当前可走的位置:
/**
* 根据当前位置计算马还能走哪些位置,并放入到一个集合中
*
* @param curPoint
* @return 该集合
*/
public static ArrayList<Point> next(Point curPoint) {
ArrayList<Point> 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;
}
然后就是实现算法:
/**
* 完成骑士周游问题的算法
*
* @param chessboard 棋盘
* @param row 当前行
* @param col 当前列
* @param step 是第几步
*/
public static void traversalChessboard(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));
//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][col] = 0;
visited[row * X + col] = false;
} else {
finished = true;
}
}
这时候其实执行速度是有点慢的,最好进行进行一定的优化。
// 根据当前这一步的所有的下一步的选择位置,进行非递减排序
public static void sort(ArrayList<Point> ps) {
ps.sort(new Comparator<Point>() {
@Override
public int compare(Point o1, Point o2) {
// TODO Auto-generated method stub
int count1 = next(o1).size();
int count2 = next(o2).size();
if (count1 < count2) {
return -1;
} else if (count1 == count2) {
return 0;
} else {
return 1;
}
}
});
}
然后把实现算法里对sort的注释给取消掉就可以了。
另附主函数代码:
private static int X;// 棋盘的列数
private static int Y;// 棋盘的行数
private static boolean[] visited;// 标记棋盘的各个位置是否被访问过
private static boolean finished;// 标记是否所有位置都被访问
public static void main(String[] args) {
X = 6;
Y = 6;
int row = 2;
int col = 4;
int[][] chessboard = new int[X][Y];
visited = new boolean[X * Y];
traversalChessboard(chessboard, row - 1, col - 1, 1);
for (int[] i : chessboard) {
System.out.println(Arrays.toString(i));
}

浙公网安备 33010602011771号