📄 main.java
字号:
package knight;
import java.util.*;
/**
* 巡游骑士,马在8*8的棋盘里跳,跳满为止~
* @author lx
*/
public class Main {
class Square {
int row, col, state;
public Square(int r, int c, int s) {
row = r;
col = c;
state = s;
}
}
Square[][] board = new Square[8][8];
// the next two arrays define moves#0 through #7
// 0 1 2 3 4 5 6 7
static int[]horizontal = {2,1,-1,-2,-2,-1,1,2};
static int[]vertical = {-1,-2,-2,-1,1,2,2,1};
int crow; // current row
int ccol; // current column
int step; // step number for tour
public Main() {
for (int i=0; i <8; i++) {
for (int j=0; j <8; j++) {
board[i][j] = new Square(i,j,0);
}
}
}
public void printBoard() {
for (int i=0; i <8; i++) {
for (int j=0; j <8; j++) {
System.out.printf("%3d",board[i][j].state);
}
System.out.printf("\n");
}
System.out.printf("\n");
}
/** Creates a new instance of Main */
// check move
//if the aquare at board[row][col] is valid,return true
//else return false
public boolean checkMove(int row, int col) {
if (row >= 0 && row <8 && col>=0 && col <8 && board[row][col].state == 0)
return true;
else
return false;
}
//nextSquare
//for a given squre sq and move id,
//calculate the possible move
//if the move possible, return square
// if the move is not possible, return null
public Square nextSquare (Square sq, int move) {
int crow = sq.row;
int ccol = sq.col;
crow += vertical[move];
ccol += horizontal[move];
if (checkMove(crow,ccol)) return board[crow][ccol];
else return null;
}
public int countMove(Square sq){
int count = 0;
for (int i = 0; i <8; i++) {
if (nextSquare(sq, i) != null) count++;
}
return count;
}
public int getMinMove(Square sq) {
int mincount = 9;
int minmove = -1;
for (int i=0; i <8; i++){
Square nextsq = nextSquare(sq,i);
if (nextsq != null) {
int count = countMove(nextsq);
if (count < mincount) {
mincount = count;
minmove = i;
}
}
}
return minmove;
}
public void autoPlay() {
Scanner scan = new Scanner(System.in);
crow = 0;
ccol = 0;
step = 1;
Square csq = board[crow][ccol];
csq.state = step;
printBoard();
while (step <64) {
step++;
int move = getMinMove(csq);
if (move == -1) {
System.out.println("No more moves, Game over");
break;
}
Square nextsq = nextSquare(csq,move);
nextsq.state = step;
csq = nextsq;
printBoard();
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Main k = new Main();
k.autoPlay();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -