Implement the N-Queens Problem - Anything to improve?

Tell us what’s happening:

This is a complete code that works for the test it’s asked, but I made it to work with more a queue than a stack (I had to reverse it later).

Tried searching for one that looked similar to mine, and asked an AI to point out (it made the same code solving it with .reverse() =P) but it also said my diagonal logic could fail in other cases, so I wanted to know if I did something wrong with it, and just made a temporary script for the challenge.

What I did wrong with my logic? why it’s not LIFO? Also, if there’s something I could have done better let me know. I tried to comment it the most I thought it was necessary to keep it simple, sorry if its still confusing. (Also, I know I shouldn’t post the fully code but I didn’t know where to ask, I’ll keep it alive for just 1 or 2 days and will be taking it off, really sorry about it)

Edit: just some misspelled. Let me know if there’s any more =P

Your code so far

def dfs_n_queens(n: int) -> list:
    results = []
    stack = [([], [False] * n)]

    while stack:
        current, visited = stack.pop()

        # if current is complete just add it to result and ignore
        if len(current) == n > 0:
            results.append(current)
            continue

        # will verify if it's valid
        for i, v in enumerate(visited):
            if v:
                continue

            # will copy the list to not modify the original one
            copy = visited.copy()
            copy[i] = True

            # if current is empty, it will create the variations it can
            if not current:
                stack.append((current + [i], copy))

            # if it's not empty, it will create new combinations
            else:
                weight = len(current)

                # It will read the current list to verify if there's a combination that does not get on diagonal
                for c in current:
                    if abs(c - i) != weight:
                        weight -= 1

                    if not weight:
                        stack.append((current+[i], copy))

    # reverse to get on the order asked
    results.reverse()
    return results

print(dfs_n_queens(6))

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:148.0) Gecko/20100101 Firefox/148.0

Challenge Information:

Implement the N-Queens Problem - Implement the N-Queens Algorithm

We have blurred this solution (with [spoiler][/spoiler] tags) so that users who have not completed this challenge can read the discussion in this thread without giving away the solution.

1 Like

ok, sorry to trouble you, will pay more attention to it, thanks!

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.