Problem:
Write an algorithm to print all ways of arranging eight queens on a chess board so that none of them share the same row, column or diagonal.
My Code:
________________________________________________________________
package alg;
import java.util.Stack;
public class EightQueens {
public static final int N = 8;
static class Queen {
public int x, y;
Queen(int x, int y) {
this.x = x;
this.y = y;
}
}
static void findAllResult() {
Stack<Queen> s = new Stack<Queen>();
for(int i = 0; i<N; i++){
Queen q = new Queen(0,i);
s.push(q);
locateNextQueen(1, s);
}
}
static void locateNextQueen(int row, Stack<Queen> queens){
if(row == N){
System.out.println("Find one result:");
for(Queen q : queens){
System.out.println("\t(" + q.x + "," + q.y + ")");
}
return;
}
for(int y = 0; y < N; y++){
boolean valid = true;
for(Queen queen : queens){
if( row == queen.x || y == queen.y ||
(queen.y - y == queen.x - row) ||
(queen.y - y == row - queen.x) ){
valid = false;
break;
}
}
if(valid == false){
continue;
}else {
Queen q = new Queen(row, y);
queens.push(q);
locateNextQueen(row+1, queens);
queens.pop();
}
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
findAllResult();
}
}
分享到:
相关推荐
n queen problem source code in working
N皇后问题,解决N皇后问题,详细的C代码
EACH INDIVIDUAL:- [1*8] 其中每列值告诉皇后在该特定列中的位置 最终解决方案:-每一行在“解决方案”矩阵中给出一个唯一的解决方案 它具有非常基本但有效的选择、交叉和变异功能。 皇后在开始时随机放置。 我是为 ...
n-Queen Problem using Tabu Search
可以实现N皇后的问题 运用简易算法 大大降低了耗时
使用Hopfield人工神经网络解决"N-皇后"问题
n皇后问题n皇后问题n皇后问题n皇后问题n皇后问题
SA algorithm for solving n-Queen problem
Practice 1 Date: Monday, March 18th, 2013 We highly encourage being environment friendly and trying all problems on your own. ...Solve the 8-Queen problem using back-tracking algorithm.
8皇后一直是C语言中的经典问题,本代码利用回溯法解决了N皇后问题
回溯算法解决n皇后问题,c++源码,可以参考
This is a simple program to help you to find the 8 Queen problem with climbhill method. Using vb6
visual c++ programmin 8 queen problem
C#,动态规划(DP)N皇后问题(N Queen Problem)的回溯(Backtracking)算法与源代码 在N*N的方格棋盘放置了N个皇后,使得它们不相互攻击(即任意2个皇后不允许处在同一排,同一列,也不允许处在与棋盘边框成45角的...
八皇后问题 Eight Queen's Problem八皇后问题演示系统
N皇后问题(n-queen problem)是一个经典的组合优化问题,也是一个使用回溯法(backtracking)的典型例子。回溯法是一种系统地搜索问题解的方法。 此文档包含算法分析、代码实现、演示程序、演示界面。
n queen problem that gives solution
8 Queen's problem is an ancient and famous, the problem is the famous 19th century mathematician Gauss 1850 : in the 8x8 grid placed on the international chess 8 Queen's, making it unable to attack ...
WPF 国际象棋 棋子ChessProgrammingTest.zip 要求: You have been provided with a third-party library ...* Queen – Moves diagonally, horizontally or vertically, any distance within board boundaries
public class ChessBoard {public static int Q= 8;private int[][] board;private int[] queenPositions;public static void main(String[] args) {boolean climb = true;int climbCount = 0;while (climb) {...