public class Queen {
private char[][] matrix;
private int size;
private int[] position;
private int result;
public int getResult() {
return result;
}
public Queen(int size) {
this.size = size;
matrix = new char[size][size];
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
matrix[i][j] = ‘x‘;
position = new int[size];
private void printMatrix() {
System.out.printf("---- sulution %d ----\n", result);
System.out.print("{");
for (int j = 0; j < size - 1; j++)
System.out.print(matrix[i][j] + " ");
System.out.print(matrix[i][size - 1]);
System.out.println("}");
private boolean isValid(int row, int col) {
for (int i = 0; i < row; i++) {
if (position[i] == position[row]) {
return false;
if (Math.abs(position[i] - position[row]) == row - i) {
return true;
public void trial(int row) {
matrix[row][i] = ‘.‘;
position[row] = i;
if (isValid(row, position[row])) {
if (row < size - 1) {
trial(row + 1);
} else {
/* success */
result++;
printMatrix();
matrix[row][i] = ‘x‘;
public static void main(String[] args) {
Queen test = new Queen(4);
test.trial(0);
System.out.printf("result is: %d", test.getResult());
public class Queen {
private char[][] matrix;
private int size;
private int[] position;
private int result;
public int getResult() {
return result;
}
public Queen(int size) {
this.size = size;
matrix = new char[size][size];
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
matrix[i][j] = ‘x‘;
}
}
position = new int[size];
}
private void printMatrix() {
System.out.printf("---- sulution %d ----\n", result);
for (int i = 0; i < size; i++) {
System.out.print("{");
for (int j = 0; j < size - 1; j++)
System.out.print(matrix[i][j] + " ");
System.out.print(matrix[i][size - 1]);
System.out.println("}");
}
}
private boolean isValid(int row, int col) {
for (int i = 0; i < row; i++) {
if (position[i] == position[row]) {
return false;
}
if (Math.abs(position[i] - position[row]) == row - i) {
return false;
}
}
return true;
}
public void trial(int row) {
for (int i = 0; i < size; i++) {
matrix[row][i] = ‘.‘;
position[row] = i;
if (isValid(row, position[row])) {
if (row < size - 1) {
trial(row + 1);
} else {
/* success */
result++;
printMatrix();
}
}
matrix[row][i] = ‘x‘;
}
}
public static void main(String[] args) {
Queen test = new Queen(4);
test.trial(0);
System.out.printf("result is: %d", test.getResult());
}
}