0

I learned that BFS has time complexity of O(E+V) on a graph. I found this SO question that mentioned that on a grid it would be O(row*col). I tried to code it using a BFS code that I found, but I think it's slower than that (since I'm checking the same cell multiple times).

I have the following code to run BFS on a maze grid:

import numpy as np
import queue
import time
import sys
sys.setrecursionlimit(2000)

def BFS(queue=None):
    
    current_index = queue.get()
    current_x,current_y = current_index[0],current_index[1]
    element = matrix[current_y,current_x]
    matrix[current_y,current_x] = 2
    print(matrix)  
    print('')       
    if element == 1: return current_x,current_y

    for n in range(current_x-1,current_x+2):
        for m in range(current_y-1,current_y+2):
            if not (n==current_x and m==current_y) \
                and n>-1 and m>-1 \
                and n<matrix.shape[0] and m<matrix.shape[1] \
                and (n,m) not in queue.queue :
                    queue.put((n,m))

    return BFS(queue)

# 0. Crate Matrix size n
n = 5
matrix = np.zeros((n,n))

# 1. Put 1 at the end goal
x = matrix.shape[0]-1
y = matrix.shape[0]-1
matrix[y,x] = 1

# 2. We are going to start at zero zero 
start_x,start_y = 0, 0

# 4. Queue for BFS
start_queue = queue.Queue()
start_queue.put((start_x,start_y))
BFSstart = time.time()
BFS_results = BFS(start_queue)
BFSend = time.time()


# Print out the statements
print('======== Given Matrix ========')
print(matrix)

print('======== Given Starting Coord ========')
print("Starting X: ",start_x," Starting Y: ",start_y)

print('======== Given Answers ========')
print("Solution by BFS: ",BFS_results, " Execution Time : ", BFSend-BFSstart)

Is there a way to modify this code, or have a different code to run BFS on a grid in such way that the time complexity will be linear?

Penguin
  • 1,923
  • 3
  • 21
  • 51
  • "since I'm checking the same cell multiple times" - checking the same cell multiple times is fine, but your frontier handling is busted, and the `queue` module is specifically designed as an inter-thread message passing system, not as a general-purpose queue library - `collections.deque` is a general-purpose queue. – user2357112 Feb 11 '21 at 16:53
  • Checking each cell multiple times doesn't affect the time complexity, as long as the number of times is bounded by a constant. In this case, that constant is the number of neighboring cells. – jasonharper Feb 11 '21 at 16:53
  • @user2357112supportsMonica Makes a lot of sense! I'll edit that – Penguin Feb 11 '21 at 18:01
  • @jasonharper Oh you're right, I didn't think about it that way. So just to verify, it is still O(row*col) in my code? – Penguin Feb 11 '21 at 18:02

0 Answers0