Last active
October 21, 2020 19:47
-
-
Save arcticOak2/dc3695c0ba3165be40f558eb36c167d5 to your computer and use it in GitHub Desktop.
My simple backtracking code for N-Queens problem
This file contains hidden or 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
public class NQueens { | |
private int[][] board; | |
public static void main(String[] args) { | |
NQueens queens = new NQueens(); | |
int size = 30; | |
queens.init(size); | |
if (queens.paintTheBoardWithQueens(0, size)) { | |
queens.printArray(); | |
} else { | |
System.out.println("No possible solution!"); | |
} | |
} | |
private void printArray() { | |
for (int i = 0; i < board.length; i++) { | |
for (int j = 0; j < board[i].length; j++) { | |
System.out.print(board[i][j] + "\t"); | |
} | |
System.out.println(); | |
} | |
System.out.println(); | |
} | |
private boolean paintTheBoardWithQueens(int level, int boardSize) { | |
int tempX = 0; | |
if (level == boardSize) { | |
return true; | |
} | |
while (tempX < boardSize) { | |
board[level][tempX] = 1; | |
boolean wasPaintedCorrectly = checkIfQueenPlacedCorrectly(tempX, level); | |
if (wasPaintedCorrectly && level < boardSize) { | |
if (paintTheBoardWithQueens(level + 1, boardSize)) { | |
return true; | |
} | |
} | |
board[level][tempX] = 0; | |
tempX++; | |
} | |
return false; | |
} | |
private void init(int n) { | |
board = new int[n][n]; | |
} | |
// Assuming y > tempY | |
private boolean checkIfTheseTwoPointsAreSafeFromEachOther(int x, int y, int tempX, int tempY) { | |
if (x == tempX) { | |
return false; | |
} | |
return Math.abs(x - tempX) != Math.abs(y - tempY); | |
} | |
private boolean checkIfQueenPlacedCorrectly(int x, int y) { | |
if (y == 0) { | |
return true; | |
} | |
int tempX = 0; | |
int tempY = y - 1; | |
while (tempY >= 0) { | |
while (board[tempY][tempX] != 1) { | |
tempX++; | |
} | |
boolean check = checkIfTheseTwoPointsAreSafeFromEachOther(x, y, tempX, tempY); | |
if (!check) { | |
return false; | |
} | |
tempX = 0; | |
tempY--; | |
} | |
return true; | |
} | |
} |
Author
arcticOak2
commented
Oct 21, 2020
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment