📄 queen.java
字号:
//The class to represent the 8*8 chessboard
class chessboard{
int [][]board = new int[8][8];
int printCount = 0;
//Initialization
chessboard(){
for(int i = 0; i < 8 ; i++)
for(int j = 0; j < 8 ; j++)
board[i][j] = 0;
}
//Put down a chess
public void putDown(int x,int y){
board[x][y] = 1;
}
//Show the chessboard
public void show(){
printCount++;
String out = "No.";
out += printCount;
out += " solution:";
out += '\n';
System.out.print(out);
for(int i = 0; i < 8 ; i++){
for(int j = 0;j < 8 ; j++){
if(board[i][j] == 1)
System.out.print('O');
else
System.out.print('X');
System.out.print(' ');
}
System.out.print('\n');
}
System.out.print('\n');
}
//Judge whether it is eligible for the game
public boolean check(int i,int j){
for (int x = 0; x < 8; x ++) {
if (i == x) continue;
if (board[x][j] == 1) return false;
int k = j - (i - x);
if ((k >= 0) && (k <= 7) && (board[x][k] == 1)) return false;
k = j + (i - x);
if ((k >= 0) && (k <= 7) && (board[x][k] == 1)) return false;
}
return true;
}
//Try to put a chess
public void put(int n){
int i;
i = 0;
for (; i < 8; i++) {
if (check(n, i)) {
putDown(n, i);
if (n == 7) {
show();
}
else
put(n + 1);
board[n][i] = 0;
}
}
}
//Show the number of arrangements
public int showCount(){
return printCount;
}
}
public class Queen {
static chessboard cb = new chessboard();
public static void main(String[] args) {
System.out.println("The possible arrangements are:");
cb.put(0);
String output = "There are totally "+ cb.showCount() +" kinds of arrangements.";
System.out.println(output);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -