Last active
April 20, 2021 07:40
-
-
Save ZviMints/88e8958355dcc97aae877963b9ed3d0f to your computer and use it in GitHub Desktop.
NQueens Counter Solution
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
// 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