Skip to content

Instantly share code, notes, and snippets.

@lya79
Last active January 31, 2018 05:28
Show Gist options
  • Select an option

  • Save lya79/6f51a1a6834229db172ccaaeedc0f888 to your computer and use it in GitHub Desktop.

Select an option

Save lya79/6f51a1a6834229db172ccaaeedc0f888 to your computer and use it in GitHub Desktop.
簡易版本_八皇后問題_使用回溯法(backtracking)
package LinkedList;
/*
* 八皇后問題
* 此程式用來描述 回溯法(backtracking)
* 並且修改題目先以四皇后進行解題
*/
public class EightQueensPuzzle {
public static void main(String[] args) {
new EightQueensPuzzle();
}
public EightQueensPuzzle() {
int total = 4;//皇后數量
int maxColumn = total;
for (int row = 0; row < maxColumn; row++) {
for (int row2 = 0; row2 < maxColumn; row2++) {
if (isError(row, row2, 1)) {
continue;
}
for (int row3 = 0; row3 < maxColumn; row3++) {
if (isError(row2, row3, 1)) {
continue;
}
if (isError(row, row3, 2)) {
continue;
}
for (int row4 = 0; row4 < maxColumn; row4++) {
if (isError(row3, row4, 1)) {
continue;
}
if (isError(row2, row4, 2)) {
continue;
}
if (isError(row, row4, 3)) {
continue;
}
System.out.println((row + 1) + "," + (row2 + 1) + "," + (row3 + 1) + "," + (row4 + 1));
}
}
}
}
}
private boolean isError(int row, int row2, int space) {
boolean error = false;
if (row == row2) {
error = true;
} else if (row == row2 + space) {
error = true;
} else if (row == row2 - space) {
error = true;
}
return error;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment