我寫了一些代碼來制作地形生成演算法,它需要“永遠”運行。我設法將問題追溯到我所做的廣度優先搜索演算法,更具體地說,前 4 個 if 陳述句檢查當前單元格的鄰居是否是可以移動到的有效點。該功能的其余部分是因為我有多個搜索同時探索不同的區域,如果兩個觸摸我洗掉其中一個。
for self.x, self.y in self.active:
# Fix from here
if grid[self.x][self.y-1] == 1 and (self.x,self.y-1) not in self.searched:
self.searched.append((self.x,self.y-1))
self.nextActive.append((self.x,self.y-1))
if grid[self.x 1][self.y] == 1 and (self.x 1,self.y) not in self.searched:
self.searched.append((self.x 1,self.y))
self.nextActive.append((self.x 1,self.y))
if grid[self.x][self.y 1] == 1 and (self.x,self.y 1) not in self.searched:
self.searched.append((self.x,self.y 1))
self.nextActive.append((self.x,self.y 1))
if grid[self.x-1][self.y] == 1 and (self.x-1,self.y) not in self.searched:
self.searched.append((self.x-1,self.y))
self.nextActive.append((self.x-1,self.y))
# to here it takes 0.00359s * about 1000 cycles
self.active = self.nextActive[:]
self.nextActive = []
if self.active == []:
self.full = True
return
for i in self.active:
for searcher in breathClassList:
if searcher == self: continue
if i in searcher.searched:
if len(self.searched) >= len(searcher.searched):
breathClassList.remove(searcher)
elif self in breathClassList: breathClassList.remove(self)
break
如果有人有任何建議讓這個運行得更快,我會全力以赴。
uj5u.com熱心網友回復:
它看起來像是self.searched一個串列(正如您所呼叫append的那樣)。在最壞的情況下,在串列中查找專案所花費的時間與串列的長度成正比(即時間復雜度為 O(n),其中 n 是長度)。
您可以做的一件事是將該串列設為一個集合,因為查找專案是在恒定時間內發生的(即隨著專案數量的增長而保持不變。時間復雜度為 O(1))。您可以在此處執行此操作,因為您正在存盤元組,而這些元組是不可變的,因此是可散列的。
uj5u.com熱心網友回復:
連同來自 ndc85430 的答案,我將在一個單獨的陣列中創建用于搜索的增量,并回圈該陣列以進行更新。這將很好地避免代碼重復(注意add在這里使用而不是append使用集合來顯示。)。
deltas = ((0, -1), (1, 0), (-1, 0), (0, 1))
for self.x, self.y in self.active:
for dx, dy in deltas:
x, y = self.x dx, self.y dy
if grid[x][y] == 1 and (x, y) not in self.searched:
self.searched.add((x, y))
self.nextActive.add((x, y))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/496714.html
下一篇:優化if條件陳述句
