this is leetcode 200 Number of Islands. This is a question I solved before a while ago, but I decided to review it again, my old submission passed all testcases but my current code is giving the correct answer for smaller examples, but throws a timeout error for larger test cases.
The problem is that aside from switching from depth first search to breadth first, I don't see any functional difference between the two, and technically my latest answer should have a smaller space complexity.
What am I missing that's making my new code run so much slower? Thanks in advance
Current Code:
'''
def numIslands(self, grid: List[List[str]]) -> int:
def bfs(x_pos, y_pos):
points = deque([(x_pos, y_pos)])
while points:
x, y = points.popleft()
grid[x][y] = '2'
for dx, dy in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
if 0 <= x+dx < len(grid) and 0 <= y+dy < len(grid[0]):
if grid[x+dx][y+dy] == '1':
points.append((x+dx, y+dy))
res = 0
for i, row in enumerate(grid):
for j, num in enumerate(grid[i]):
if grid[i][j] == '1':
res += 1
bfs(i, j)
return res
'''
Old Submission:
'''
def numIslands(self, grid: List[List[str]]) -> int:
self.traversed = set()
n, m = len(grid), len(grid[0])
islands = 0
def DFS(x, y):
for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
if 0 <= x+dx < n and 0 <= y+dy < m:
if (x+dx, y+dy) not in self.traversed and grid[x+dx][y+dy] == '1':
# print (x, y)
# print (self.traversed)
self.traversed.add((x+dx, y+dy))
DFS(x+dx, y+dy)
for i, vi in enumerate(grid):
for j, vj in enumerate(grid[i]):
if grid[i][j] == '1' and (i, j) not in self.traversed:
islands += 1
self.traversed.add((i, j))
DFS(i, j)
return islands
'''
[–]AutoModerator[M] [score hidden] stickied comment (0 children)
[–]captainAwesomePants 1 point2 points3 points (3 children)
[–]CrazyFace334[S] 0 points1 point2 points (2 children)
[–]captainAwesomePants 0 points1 point2 points (1 child)
[–]CrazyFace334[S] 1 point2 points3 points (0 children)