0

I try to solve the problem of N queens solution and want to print all possible values in a list of lists.

For example if n = 4 (size of board 4*4), the result should be [[(0, 2), (1, 0), (2, 3), (3, 1)], [(0, 2), (1, 0), (2, 3), (3, 1)]]

You can see my code below, and my question is: at the line where I remove the invalid position: self.remove_queen(row, col), the item in 'res' variable also be removing. How can I solve this problem? Thanks

Here is my Code:

class Solution:
    def __init__(self):
        self.queens_pos = []
        self.res = []

    def is_not_under_attack(self, row, col):
        if not self.queens_pos:
            return True
        for queen_pos in self.queens_pos:
            if (queen_pos[0] == row) or (queen_pos[1] == col) or (queen_pos[0] + queen_pos[1] == row + col) or (queen_pos[0] - queen_pos[1] == row - col):
                return False
        return True

    def place_queen(self, row, col):
        self.queens_pos.append((row, col))

    def remove_queen(self, row, col):
        self.queens_pos.pop(row)

    def backtrack_queen(self, n, row=0, res = []):
        for col in range(n):
            if self.is_not_under_attack(row, col):
                self.place_queen(row, col)

                if row + 1 == n:
                    res.append(self.queens_pos)
                    print(res)
                else:
                    res = self.backtrack_queen(n, row + 1, res)

                self.remove_queen(row, col)
        
        return res 


my_solution = Solution()
count = my_solution.backtrack_queen(4)

print(count)
  • Does this answer your question? [List changes unexpectedly after assignment. Why is this and how to prevent it?](https://stackoverflow.com/questions/2612802/list-changes-unexpectedly-after-assignment-why-is-this-and-how-to-prevent-it) – flyx Apr 23 '21 at 11:56
  • You shouldn't use the default function parameter `res=[]`: it is generally not what you want. See [this question/answer](https://stackoverflow.com/questions/366422/what-is-the-pythonic-way-to-avoid-default-parameters-that-are-empty-lists) or [the remark on mutable default parameters](https://docs.python.org/3/reference/compound_stmts.html#function-definitions). I'm not sure it's enough to fix your issue, but it's worth starting fixing that. – Demi-Lune Apr 23 '21 at 12:38
  • By the way, you have `self.res` in `__init__` but don't use it. Could you clarify? Did you mean `self.res` all along? – Demi-Lune Apr 23 '21 at 13:13

0 Answers0