Java代码实现利用栈解决骑士游历问题,并打印出路径坐标,实例化
时间: 2024-05-02 20:16:58 浏览: 44
骑士游历程序的开发 java
以下是Java代码实现利用栈解决骑士游历问题,并打印出路径坐标:
```java
import java.util.Stack;
public class KnightTour {
private int size;
private int[][] board;
private int[] xMoves = {2, 1, -1, -2, -2, -1, 1, 2};
private int[] yMoves = {1, 2, 2, 1, -1, -2, -2, -1};
public KnightTour(int size) {
this.size = size;
this.board = new int[size][size];
}
public void solve() {
Stack<Pair> stack = new Stack<>();
stack.push(new Pair(0, 0));
int moveCount = 0;
while (!stack.isEmpty()) {
Pair current = stack.pop();
int x = current.x;
int y = current.y;
board[x][y] = ++moveCount;
if (moveCount == size * size) {
printSolution();
return;
}
for (int i = 0; i < 8; i++) {
int nextX = x + xMoves[i];
int nextY = y + yMoves[i];
if (isValidMove(nextX, nextY)) {
stack.push(new Pair(nextX, nextY));
}
}
}
System.out.println("No solution found");
}
private boolean isValidMove(int x, int y) {
if (x < 0 || x >= size || y < 0 || y >= size) {
return false;
}
return board[x][y] == 0;
}
private void printSolution() {
System.out.println("Solution:");
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
private static class Pair {
int x;
int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
public static void main(String[] args) {
KnightTour tour = new KnightTour(8);
tour.solve();
}
}
```
在`main`方法中,我们实例化了一个`KnightTour`对象,并调用`solve`方法来解决骑士游历问题。在`solve`方法中,我们使用了一个栈来保存当前走到的位置,并依次进行下一步的尝试,直到找到解决方案或栈为空。在找到解决方案时,我们会打印出路径坐标。
阅读全文