package com.zhang.csdn;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
class EightQueen {
private static int total = 0;
private final static int EIGHT_QUEEN_ROW = 8;
private final static int EIGHT_QUEEN_COLUMN = 8;
private final static String RESULT_FILE_DISK = "E:";
private final static String RESULT_FILE_NAME = "EightQueen.txt";
private final static char RESULT_OTHER_CHAR = '*';
private final static char RESULT_QUEEN_CHAR = 'Q';
private final static String RESULT_LINE_SEPARATOR = "\r\n";
private final static String RESULT_EACH_SEPARATOR = "\r\n";
private final int[] column = new int[EIGHT_QUEEN_ROW];
private StringBuffer result = new StringBuffer();
public void execute() {
this.initColumn();
this.permute(0);
this.displayResult();
}
private void displayResult() {
System.out.println("total : " + total);
this.writeToFile(this.result);
}
private void initColumn() {
for (int i = 0; i < EIGHT_QUEEN_ROW; i++) {
column[i] = i;
}
}
private void permute(int index) {
if (index == EIGHT_QUEEN_ROW) {
if (isValid()) {
print();
total++;
}
} else {
for (int i = index; i < EIGHT_QUEEN_ROW; i++) {
swap(i, index);
permute(index + 1);
swap(i, index);
}
}
}
private void print() {
this.appendToResult();
}
private StringBuffer eachLine(int rowIndex) {
StringBuffer line = new StringBuffer(EIGHT_QUEEN_COLUMN);
for (int columnIndex = 0; columnIndex < EIGHT_QUEEN_COLUMN; columnIndex++) {
line.append( (column[rowIndex] != columnIndex ?
EightQueen.RESULT_OTHER_CHAR : EightQueen.RESULT_QUEEN_CHAR) );
}
return line.append(EightQueen.RESULT_LINE_SEPARATOR);
}
private void appendToResult() {
StringBuffer singleAnswer = new StringBuffer();
for (int rowIndex = 0; rowIndex < EIGHT_QUEEN_ROW; rowIndex++) {
singleAnswer.append(eachLine(rowIndex));
}
result.append(singleAnswer).append(EightQueen.RESULT_EACH_SEPARATOR);
}
private static void writeToFile(StringBuffer sb) {
FileWriter writer = null;
try {
File file = new File( EightQueen.RESULT_FILE_DISK +
File.separator +
EightQueen.RESULT_FILE_NAME);
if (!file.exists()) {
file.createNewFile();
}
writer = new FileWriter(file);
writer.write(sb.toString());
writer.flush();
writer.close();
} catch(Exception e) {
e.printStackTrace();
} finally {
}
}
private void swap(int i, int j) {
int temp = column[i];
column[i] = column[j];
column[j] = temp;
}
private boolean isValid() {
for (int firstLayer = 0; firstLayer < EIGHT_QUEEN_COLUMN; firstLayer++) {
for (int secondLayer = firstLayer + 1; secondLayer < EIGHT_QUEEN_COLUMN; secondLayer++) {
if ( ((firstLayer - secondLayer) == (column[firstLayer] - column[secondLayer])) ||
((firstLayer - secondLayer) == (column[secondLayer] - column[firstLayer])) ) {
return false;
}
}
}
return true;
}
}
著名的八皇后问题
最新推荐文章于 2021-07-28 20:20:40 发布