Created
August 7, 2019 16:02
-
-
Save RitamChakraborty/8833e24f72a3c25ee6853c5bf5bf1305 to your computer and use it in GitHub Desktop.
N-Queens Problem implemented in java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class NQueensProblem { | |
private static int n; | |
private static char[][] arr; | |
private static LinkedHashSet<String> finalSolution; | |
static { | |
finalSolution = new LinkedHashSet<>(); | |
} | |
private static void cleanRow(int i) { | |
Arrays.fill(arr[i], ' '); | |
} | |
private static boolean verticalIsSafe(int i , int j) { | |
while (i >= 0) { | |
if (arr[i--][j] != ' ') { | |
return false; | |
} | |
} | |
return true; | |
} | |
private static boolean leftDiagonalIsSafe(int i, int j) { | |
while (i >= 0 && j >= 0) { | |
if (arr[i--][j--] != ' ') { | |
return false; | |
} | |
} | |
return true; | |
} | |
private static boolean rightDiagonalIsSafe(int i, int j) { | |
while (i >= 0 && j < n) { | |
if (arr[i--][j++] != ' ') { | |
return false; | |
} | |
} | |
return true; | |
} | |
private static boolean isSafePosition(int i, int j) { | |
return verticalIsSafe(i, j) && leftDiagonalIsSafe(i, j) && rightDiagonalIsSafe(i, j); | |
} | |
private static boolean checkBoard() { | |
for (char[] a: arr) { | |
boolean emptyRow = true; | |
for (char b: a) { | |
if (b != ' ') { | |
emptyRow = false; | |
} | |
} | |
if (emptyRow) { | |
return false; | |
} | |
} | |
return true; | |
} | |
private static void addSolution(int[] sol) { | |
if (checkBoard()) { | |
StringBuilder stringBuilder = new StringBuilder(); | |
HashSet<Integer> hashSet = new HashSet<>(); | |
for (int a: sol) { | |
if (a == -1 || hashSet.contains(a)) { | |
return; | |
} else { | |
hashSet.add(a); | |
stringBuilder.append(a); | |
} | |
} | |
if (!finalSolution.contains(stringBuilder.toString())) { | |
System.out.println(stringBuilder.toString()); | |
Arrays.stream(arr).forEach(a -> System.out.println(Arrays.toString(a))); | |
System.out.println(); | |
} | |
finalSolution.add(stringBuilder.toString()); | |
} | |
} | |
private static void func(int i, int[] sol) { | |
if (i != n) { | |
for (int j = 0; j < n; j++) { | |
if (i == 0) { | |
Arrays.fill(sol, -1); | |
} | |
cleanRow(i); | |
if (isSafePosition(i, j)) { | |
arr[i][j] = 'Q'; | |
sol[i] = j; | |
func(i + 1, sol); | |
addSolution(sol); | |
} | |
} | |
} | |
} | |
public static void main(String[] args) { | |
n = 5; | |
arr = new char[n][n]; | |
int[] sol = new int[n]; | |
Arrays.stream(arr).forEach(a -> Arrays.fill(a, ' ')); | |
func(0, sol); | |
System.out.println(finalSolution); | |
System.out.println(finalSolution.size()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment