Skip to content

Instantly share code, notes, and snippets.

@vmayakumar
Created August 29, 2019 00:14
Show Gist options
  • Save vmayakumar/cbc27bb44f6b0b00ed38ea5bc9c5be49 to your computer and use it in GitHub Desktop.
Save vmayakumar/cbc27bb44f6b0b00ed38ea5bc9c5be49 to your computer and use it in GitHub Desktop.
8 queen problem
package com.algorithms;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class NQueen {
class Position {
int row;
int col;
public Position(int row, int col) {
this.row = row;
this.col = col;
}
public String toString() {
return "[ " + row + "," + col + " ]";
}
}
public List<List<String>> solveNQueens(int n) {
List<List<String>> result = new ArrayList<>();
Position[] positions = new Position[n];
solve(0, positions, result, n);
return result;
}
public void solve(int row, Position[] positions, List<List<String>> result, int n) {
if (n == row) {
StringBuffer buff = new StringBuffer();
List<String> oneResult = new ArrayList<>();
for (Position p : positions) {
for (int i = 0; i < n; i++) {
if (p.col == i) {
buff.append("Q");
} else {
buff.append(".");
}
}
oneResult.add(buff.toString());
buff = new StringBuffer();
}
buff.append("\n");
result.add(oneResult);
return;
}
for (int col = 0; col < n; col++) {
boolean found = true;
for (int queen = 0; queen < row; queen++) {
if (positions[queen].col == col || positions[queen].col - positions[queen].row == col - row || positions[queen].row + positions[queen].col == col + row) {
found = false;
break;
}
}
if (found) {
positions[row] = new Position(row, col);
solve(row + 1, positions, result, n);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment