微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

有没有办法在线性时间内在网格上运行 BFS?即关于列数和行数——O(rows*cols)

如何解决有没有办法在线性时间内在网格上运行 BFS?即关于列数和行数——O(rows*cols)

我了解到 BFS 在图上的时间复杂度为 O(E+V)。我发现 this SO question 提到在网格上它将是 O(row*col)。我尝试使用找到的 BFS 代码对其进行编码,但我认为它比这慢(因为我多次检查同一个单元格)。

我有以下代码在迷宫网格上运行 BFS:

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)

有没有办法修改这个代码,或者有一个不同的代码在网格上运行 BFS,这样时间复杂度就会是线性的?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。