Skip to content

Instantly share code, notes, and snippets.

@ZviMints
Last active April 20, 2021 07:40
Show Gist options
  • Save ZviMints/88e8958355dcc97aae877963b9ed3d0f to your computer and use it in GitHub Desktop.
Save ZviMints/88e8958355dcc97aae877963b9ed3d0f to your computer and use it in GitHub Desktop.
NQueens Counter Solution
// https://leetcode.com/problems/n-queens-ii/
object Solution extends App {
def totalNQueens(N: Int): Int = {
type Board = Array[Array[Boolean]]
def putQueen(board: Board, row: Int, col: Int): Unit = board(row)(col) = true
def removeQueen(board: Board, row: Int, col: Int): Unit = board(row)(col) = false
def isValid(board: Board, row: Int, col: Int): Boolean = {
val checkCol = (0 until row).forall(currRow => board(currRow)(col) == false )
val checkLeftDiagonal = ((row to 0 by -1) zip (col to 0 by -1)).forall { case (currRow, currCol) => board(currRow)(currCol) == false }
val checkRightDiagonal = ((row to 0 by -1) zip (col until N)).forall { case (currRow, currCol) => board(currRow)(currCol) == false }
checkCol && checkLeftDiagonal && checkRightDiagonal
}
def countQueenPlacements(board: Board, row: Int)(soFarPlaces: Int): Int = {
def isFinished = { soFarPlaces == N }
if(isFinished) 1
else {
var solutions = 0
(0 until N).foreach { col =>
if(isValid(board, row, col)) {
putQueen(board, row, col)
solutions += countQueenPlacements(board, row + 1)(soFarPlaces + 1)
removeQueen(board, row, col)
}
}
solutions
}
}
countQueenPlacements(Array.tabulate(N, N)((_, _) => false), 0)(0)
}
print(totalNQueens(8))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment