解题思路:
1.先打印整张棋盘的边界线,‘|’与‘|’之间填充空格;
2. except数组存放棋盘上已经放置了Queen的下标,例如第一行Q的下标为1,则第二行Q的下标index !=1 && index != 1+2 && index != 1-2, && index != (0~16之间的偶数),以此类推。
/*
|Q| | | | | | | |
| | | | | | |Q| |
| | | |Q| | | | |
| | | | | | | |Q|
| |Q| | | | | | |
| | | | |Q| | | |
| | |Q| | | | | |
| | | | | |Q| | |
******************
| | | | | | | |Q|
| | |Q| | | | | |
| | | | | | |Q| |
| | | |Q| | | | |
| | | | | |Q| | |
|Q| | | | | | | |
| | | | |Q| | | |
| |Q| | | | | | |
*/
public class EightQueen {
public static void main(String[] args) {
final int COLUMN = 17;
final int LINE = 8;
char[][] pattern = new char[LINE][COLUMN];
drawPattern(pattern, LINE, COLUMN);
drawQueen(pattern, LINE, COLUMN);
printPatternBoard(pattern, LINE, COLUMN);
}
public static void drawPattern(char[][] pa, final int LINE, final int COLUMN) {
for (int i = 0, j; i < LINE; i++) {
for (j = 0; j < COLUMN - 1; j++) {
pa[i][j++] = '|';
pa[i][j] = ' ';
}
pa[i][j] = '|';
}
}
public static void printPatternBoard(char[][] pa, final int LINE, final int COLUMN) {
for (int i = 0; i < LINE; i++) {
for (int j = 0; j < COLUMN; j++)
System.out.print(pa[i][j]);
System.out.println();
}
}
public static void drawQueen(char[][]pa, final int LINE, final int COLUMN) {
int temp = 0, k;
int[] except = new int[LINE];
for (int i = 1, j = 0; i < COLUMN; i += 2, j++) {
while (i == 1) {
temp = (int)(1 + Math.random() * 15);
//Queen只能存放在下标为:1、3、5、7、9、11、13、15的位置,下标为:2、4、6、8、10、12、14、16为‘|’的位置。
if (temp % 2 != 0)
break;
}
while (i > 1) {
temp = (int) (1 + Math.random() * 15);
for (k = j; k > 0; k--) {
if (k == j) {
if (temp == except[k - 1] || temp == (except[k - 1] + 2) || temp == (except[k - 1] - 2) || temp % 2 == 0)
break;
}
else if (temp == except[k - 1] || temp % 2 == 0)
break;
}
if (k == 0)
break;
}
pa[j][temp] = 'Q';
except[j] = temp;
}
}
}