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

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

There is a newer version: 1.8
Show newest version
// #Hard #Top_100_Liked_Questions #Array #Backtracking #Big_O_Time_O(N!)_Space_O(N)
// #2024_06_23_Time_8_ms_(98.15%)_Space_16_MB_(94.44%)

public class Solution {
    public func solveNQueens(_ n: Int) -> [[String]] {
        var pos = [Bool](repeating: false, count: n + 2 * n - 1 + 2 * n - 1)
        var pos2 = [Int](repeating: 0, count: n)
        var ans = [[String]]()
        helper(n, 0, &pos, &pos2, &ans)
        return ans
    }

    private func helper(_ n: Int, _ row: Int, _ pos: inout [Bool], _ pos2: inout [Int], _ ans: inout [[String]]) {
        if row == n {
            construct(n, pos2, &ans)
            return
        }
        for i in 0..




© 2015 - 2025 Weber Informatics LLC | Privacy Policy