问题
READ CAREFULLY BEFORE MARKING AS DUPLICATE!
I have a 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
You CANNOT move diagonally in the matrix!
I want to find ALL possible paths between the two 'x's. The only condition is, that the path cannot cross itself (so no cycles). Apparently the DSF algorithm would not find every single path (to understand why, see this paper: http://www.algolist.net/Algorithms/Graph/Undirected/Depth-first_search).
So what algorithms should else be used?
回答1:
DFS without a visited set WILL find all paths in a graph.
You will have to maintain a special visited set variation that is relevant only for the current path, and not global. To do so, every time you "finish" exploring a vertex, you will have to remove it from the set.
pseudo code:
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()
Complexity of this solution is exponential, but it is expected since there are exponential number of simple paths between two nodes.
回答2:
My specialty!
Haskell code:
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)
回答3:
I was interested in the same problem as OP. I have read about it and was difficult to find a proper solution. Many solutions have a graphs approach but not matrix. The comment of @amit and this link help me alot.
Here you can find a working solution: https://repl.it/@gmunumel/StarryUniqueLicense
来源:https://stackoverflow.com/questions/16498066/finding-all-paths-between-2-points-on-a-square-matrix