I'm trying to solve theN-Queues as following:
class Solution(object):
def __init__(self):
self.queues = []
def DFS(self, n, row, col, pie, na, path):
if row == n:
print 'current recursion path: ', path
self.queues.append(path)
print 'paths within the recursion: ', self.queues
return
for c in range(n):
if (c not in col) and (c + row not in pie) and (row-c not in na):
col.add(c)
pie.add(c+row)
na.add(row-c)
# self.queues.append(c)
# path += str(c)
path.append(c)
# print 'row: ', row, 'col: ', c, path
self.DFS(n, row + 1, col, pie, na, path)
col.remove(c)
pie.remove(c+row)
na.remove(row-c)
# path = path[:-1]
path.pop()
# else:
# path.pop()
return None
# print '\n'
def solveNQueens(self, n):
"""
:type n: int
:rtype: List[List[str]]
"""
col = set()
pie = set()
na = set()
print 'before recursion: ', self.queues
self.DFS(n, 0, col, pie, na, [])
print 'after recursion: ', self.queues
# return self.reslutPrint(n)
I got the following print out:
before recursion: []
current recursion path: [1, 3, 0, 2]
paths within the recursion: [[1, 3, 0, 2]]
current recursion path: [2, 0, 3, 1]
paths within the recursion: [[2, 0, 3, 1], [2, 0, 3, 1]]
after recursion: [[], []]
As you can see, the recursion is getting the correct answer for each path, however, the answer is not appended to the global variable self.queues
correctly. Can you please let me know why is this happening?
I'm guessing this is due to that when I appended the list to self.queues
, it's giving the address instead of the actual value to self.queues
. If so, how can I fix this?
Thanks a lot.
Ian