[英]Finding ALL paths between 2 points on a square Matrix
重復標記之前請仔細閱讀!
我有一個矩陣:
0 0 0 x 0
0 0 0 0 0
0 0 0 0 0
0 x 0 0 0
0 0 0 0 0
您不能在矩陣中對角移動!
我想找到兩個“ x”之間的所有可能路徑。 唯一的條件是,路徑不能自身交叉(因此沒有循環)。 顯然,DSF算法無法找到每個單獨的路徑(要了解原因,請參閱本文: http : //www.algolist.net/Algorithms/Graph/Undirected/Depth-first_search )。
那么還應該使用什么算法?
沒有訪問集的DFS將在圖中找到所有路徑。
您將必須維護一個特殊的訪問集變體,該變體僅與當前路徑相關,而不與全局相關。 為此,每次“完成”探索頂點時,都必須將其從集合中刪除。
偽代碼:
DFS(source,target,visited,path):
if (source == target): //stop clause
print path
return
for each son v of source:
if v is in visited: //the vertex is already in the current path
continue
path.append(v)
visited.add(v)
DFS(v,target,visited,path)
visited.remove(v)
path.deleteLast()
該解決方案的復雜度是指數級的,但是由於兩個節點之間的簡單路徑的數量是指數級的,因此可以預期。
我的專長!
Haskell代碼:
import Control.Monad (guard)
paths (a,b) (a',b') m n = solve [(a',b')] where
solve result@((y,x):_) = do
next@(y',x') <- [(y,x + 1),(y,x - 1),(y + 1,x),(y - 1,x)]
guard (y' >= 0 && y' < m && x' >= 0 && x' < n && notElem (y',x') result)
if next == (a,b) then [(next:result)] else solve (next:result)
OUTPUT:
*Main> take 2 . paths (0,3) (3,1) 5 $ 5
[[(0,3),(0,2),(0,1),(0,0),(1,0),(1,1),(1,2),(1,3),(1,4),(2,4),(2,3),(2,2),(2,1),(2,0),(3,0),(4,0),(4,1),(4,2),(4,3),(4,4),(3,4),(3,3),(3,2),(3,1)]
,[(0,3),(0,2),(0,1),(1,1),(1,2),(1,3),(1,4),(2,4),(2,3),(2,2),(2,1),(2,0),(3,0),(4,0),(4,1),(4,2),(4,3),(4,4),(3,4),(3,3),(3,2),(3,1)]]
(0.02 secs, 1595416 bytes)
*Main> length . paths (0,3) (3,1) 5 $ 5
4914
(1.28 secs, 100724732 bytes)
*Main Data.List Data.Ord> minimumBy (comparing length) . paths (0,3) (3,1) 5 $ 5
[(0,3),(1,3),(2,3),(3,3),(3,2),(3,1)]
(1.42 secs, 101955224 bytes)
我對與OP相同的問題感興趣。 我已經讀過它,很難找到合適的解決方案。 許多解決方案都有圖方法,但沒有矩陣。 @amit的評論和此鏈接對我有很大幫助。
在這里您可以找到一個可行的解決方案: https : //repl.it/@gmunumel/StarryUniqueLicense
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.