在8X8空棋盘上摆放八个皇后,并使其中任意两个皇后不能在同一行或同一列或同一对角线
代码:
package test;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
public class Queen {
int[] a = new int[8];
int[] b = new int[15];
int[] c = new int[15];
int[][] Queen = new int[8][8];
void next(int i) {
for (int j = 0; j < 8; j++) {
if (a[j] == 0 && b[i + j] == 0 && c[i - j + 7] == 0) {
a[j] = b[i + j] = c[i - j + 7] = 1;
Queen[i][j] = 1;
if (i < 7)
next(i + 1);
else {
String output = new String();
for (int m = 0; m < 8; m++) {
for (int n = 0; n < 8; n++)
output += " " + Queen[m][n] + " ";
output += "\n";
}
JTextArea outputArea = new JTextArea();
outputArea.setText(output);
JOptionPane.showMessageDialog(null, outputArea,
"One possible distribution",
JOptionPane.INFORMATION_MESSAGE);
}
a[j] = b[i + j] = c[i - j + 7] = Queen[i][j] = 0;
}
}
}
public static void main(String args[]) {
Queen one = new Queen();
one.next(0);
System.exit(0);
}
}