All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0001_0100.s0051_n_queens.Solution.kt Maven / Gradle / Ivy

There is a newer version: 1.30
Show newest version
package g0001_0100.s0051_n_queens

// #Hard #Top_100_Liked_Questions #Array #Backtracking
// #2022_08_29_Time_243_ms_(95.10%)_Space_39.7_MB_(91.18%)

import java.util.Arrays

class Solution {
    fun solveNQueens(n: Int): List> {
        val pos = BooleanArray(n + 2 * n - 1 + 2 * n - 1)
        val pos2 = IntArray(n)
        val ans: MutableList> = ArrayList()
        helper(n, 0, pos, pos2, ans)
        return ans
    }

    private fun helper(n: Int, row: Int, pos: BooleanArray, pos2: IntArray, ans: MutableList>) {
        if (row == n) {
            construct(n, pos2, ans)
            return
        }
        for (i in 0 until n) {
            val index = n + 2 * n - 1 + n - 1 + i - row
            if (pos[i] || pos[n + i + row] || pos[index]) {
                continue
            }
            pos[i] = true
            pos[n + i + row] = true
            pos[index] = true
            pos2[row] = i
            helper(n, row + 1, pos, pos2, ans)
            pos[i] = false
            pos[n + i + row] = false
            pos[index] = false
        }
    }

    private fun construct(n: Int, pos: IntArray, ans: MutableList>) {
        val sol: MutableList = ArrayList()
        for (r in 0 until n) {
            val queenRow = CharArray(n)
            Arrays.fill(queenRow, '.')
            queenRow[pos[r]] = 'Q'
            sol.add(String(queenRow))
        }
        ans.add(sol)
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy