Exponential blow up of BFS

Правка en1, от tyristik, 2025-04-03 13:50:40

Imagine doing bfs on a 2D $$$n \times n$$$ grid. Your code may look something like this:

import collections
NOT_VISITED, VISITED = 0, 1
n = int(input())
grid = [[NOT_VISITED] * n for i in range(n)]
queue = collections.deque([(0, 0)])
while len(queue):
    x, y = queue.popleft()
    for nx, ny in [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]:
        if 0 <= nx < n and 0 <= ny < n and grid[nx][ny] == NOT_VISITED:
            queue.append((nx, ny))
            grid[nx][ny] = VISITED
print(grid)

It works in $$$O(n^2)$$$, nothing interesting. But if we write it like this:

import collections
NOT_VISITED, VISITED = 0, 1
n = int(input())
grid = [[NOT_VISITED] * n for i in range(n)]
queue = collections.deque([(0, 0)])
while len(queue):
    x, y = queue.popleft()
    grid[x][y] = VISITED
    for nx, ny in [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]:
        if 0 <= nx < n and 0 <= ny < n and grid[nx][ny] == NOT_VISITED:
            queue.append((nx, ny))
print(grid)

The code now works in $$$O\left(\dfrac{4^n}{\sqrt{n}}\right)$$$ :skull: :skull: :skull:

Can you figure out why?

Теги bfs, exponential, blow, up

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en1 Английский tyristik 2025-04-03 13:50:40 1170 Initial revision (published)