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?