I am trying to solve this leetcode question: https://leetcode.com/problems/number-of-islands/
visited: List[List[int]] = None
def numIslands(self, grid: List[List[str]]) -> int:
self.visited = [[0] * len(grid[0])] * len(grid)
m, n = 0, 0
islands = 0
while m < len(grid):
while n < len(grid[0]):
print(m,n)
islands = self.recur(grid,m,n,islands)
n = n + 1
m = m +1
return islands
def recur(self, grid: List[List[str]],m: int, n: int, islands: int) -> int:
print(m,n,grid[m][n])
if grid[m][n] == "1" and self.visited[m][n] == 0:
down, right = None, None
if m < len(grid) - 1:
down = self.recur(grid,m+1, n, islands)
if n < len(grid[0]) - 1:
right = self.recur(grid,m, n+1, islands)
if right is not None and down is not None:
islands = min(islands,down,right) + 1
elif right is not None:
islands = min(islands,right) + 1
elif down is not None:
islands = min(islands,down) + 1
else:
islands = islands + 1
self.visited[m][n] = 1
print(self.visited)
return islands
My idea is to use recursion and if 1 is encountered keep going downwards and then towards right until a zero is encountered. I wanted to use a visited
variable to keep track of all the already visited values in grid
and skip recursion for those.
But I noticed that wrong cells are getting updated in visited
:
for the first iteration, m =0 and n =0, here is the output:
0 0
0 0 1
1 0 1
2 0 1
3 0 0
[[1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0]]
2 1 1
3 1 0
[[1, 1, 0, 0, 0], [1, 1, 0, 0, 0], [1, 1, 0, 0, 0], [1, 1, 0, 0, 0]]
2 2 0
[[1, 1, 1, 0, 0], [1, 1, 1, 0, 0], [1, 1, 1, 0, 0], [1, 1, 1, 0, 0]]
[[1, 1, 1, 0, 0], [1, 1, 1, 0, 0], [1, 1, 1, 0, 0], [1, 1, 1, 0, 0]]
[[1, 1, 1, 0, 0], [1, 1, 1, 0, 0], [1, 1, 1, 0, 0], [1, 1, 1, 0, 0]]
1 1 1
[[1, 1, 1, 0, 0], [1, 1, 1, 0, 0], [1, 1, 1, 0, 0], [1, 1, 1, 0, 0]]
[[1, 1, 1, 0, 0], [1, 1, 1, 0, 0], [1, 1, 1, 0, 0], [1, 1, 1, 0, 0]]
0 1 1
[[1, 1, 1, 0, 0], [1, 1, 1, 0, 0], [1, 1, 1, 0, 0], [1, 1, 1, 0, 0]]
[[1, 1, 1, 0, 0], [1, 1, 1, 0, 0], [1, 1, 1, 0, 0], [1, 1, 1, 0, 0]]
All the 3 digits lines indicate the m
, n
and grid[m][n]
values each time the recur
method is called. I am printing the visited
at the end of the method. I notice that the m
, n
values that were not visited were also getting updated to 1
in visited
.
I am not able to figure out why this is happening and it's giving me a wrong result. Any help would be appreciated.
self.visited = [[0] * len(grid[0])] * len(grid)
is going to give you issues. Initializing a 2D array like this causes references to the same mutable object (in this case [0]
) within your list items. In other words, modifying visited[0][0]
changes all elements in visited[0]
.
Try something like this:
visited = [['0'] * len(grid[0]) for _ in range(len(grid))]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.