For the Leetcode question "Number of islands," I am trying to determine the SPACE complexity for the Breadth First Search solution.
from collections import deque
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
num_islands = 0
num_row, num_col = len(grid), len(grid[0])
for r in range(num_row):
for c in range(num_col):
if grid[r][c] == '1':
num_islands += 1
self.bfs(r, c, grid)
return num_islands
def bfs(
self,
row: int,
col: int,
grid: List[List[str]]
) -> None:
queue = deque([(row, col)])
while queue:
r, c = queue.popleft()
if grid[r][c] != '1':
continue
grid[r][c] = 'X'
if r+1 <= len(grid)-1 and grid[r+1][c] == '1':
queue.append((r+1, c))
if r-1 >= 0 and grid[r-1][c] == '1':
queue.append((r-1, c))
if c+1 <= len(grid[0])-1 and grid[r][c+1] == '1':
queue.append((r, c+1))
if c-1 >= 0 and grid[r][c-1] == '1':
queue.append((r, c-1))
I am looking at this SO answer, but that example doesn't really elaborate on how exactly worst case BFS space complexity = O(M · N), where M = # of rows and N = number of columns. It states that the queue will have all of the leaf nodes, but how will that be? Also, how are all of the leaf nodes proportional to M · N? I think that diagram makes it hard to conceptualize.
I worked out a few examples, and I definitely see some cases where BFS space complexity > O(Max(M, N)), but can't grasp how it can be O(M·N) worst case. Can someone please explain, preferably with a visual walkthrough?
Example with space complexity = O(Min(M, N)) if you start at top-left corner, but > O(Max(M, N)) if you start in the middle:
[
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1]
]
A visual example like the one above will be easier to digest.