Find the paths between two given nodes?

前端 未结 8 2124
隐瞒了意图╮
隐瞒了意图╮ 2020-11-27 11:55

Say I have nodes connected in the below fashion, how do I arrive at the number of paths that exist between given points, and path details?

1,2 //node 1 and 2         


        
8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-27 12:35

    Dijkstra's algorithm applies more to weighted paths and it sounds like the poster was wanting to find all paths, not just the shortest.

    For this application, I'd build a graph (your application sounds like it wouldn't need to be directed) and use your favorite search method. It sounds like you want all paths, not just a guess at the shortest one, so use a simple recursive algorithm of your choice.

    The only problem with this is if the graph can be cyclic.

    With the connections:

    • 1, 2
    • 1, 3
    • 2, 3
    • 2, 4

    While looking for a path from 1->4, you could have a cycle of 1 -> 2 -> 3 -> 1.

    In that case, then I'd keep a stack as traversing the nodes. Here's a list with the steps for that graph and the resulting stack (sorry for the formatting - no table option):

    current node (possible next nodes minus where we came from) [stack]

    1. 1 (2, 3) [1]
    2. 2 (3, 4) [1, 2]
    3. 3 (1) [1, 2, 3]
    4. 1 (2, 3) [1, 2, 3, 1] //error - duplicate number on the stack - cycle detected
    5. 3 () [1, 2, 3] // back-stepped to node three and popped 1 off the stack. No more nodes to explore from here
    6. 2 (4) [1, 2] // back-stepped to node 2 and popped 1 off the stack.
    7. 4 () [1, 2, 4] // Target node found - record stack for a path. No more nodes to explore from here
    8. 2 () [1, 2] //back-stepped to node 2 and popped 4 off the stack. No more nodes to explore from here
    9. 1 (3) [1] //back-stepped to node 1 and popped 2 off the stack.
    10. 3 (2) [1, 3]
    11. 2 (1, 4) [1, 3, 2]
    12. 1 (2, 3) [1, 3, 2, 1] //error - duplicate number on the stack - cycle detected
    13. 2 (4) [1, 3, 2] //back-stepped to node 2 and popped 1 off the stack
    14. 4 () [1, 3, 2, 4] Target node found - record stack for a path. No more nodes to explore from here
    15. 2 () [1, 3, 2] //back-stepped to node 2 and popped 4 off the stack. No more nodes
    16. 3 () [1, 3] // back-stepped to node 3 and popped 2 off the stack. No more nodes
    17. 1 () [1] // back-stepped to node 1 and popped 3 off the stack. No more nodes
    18. Done with 2 recorded paths of [1, 2, 4] and [1, 3, 2, 4]

提交回复
热议问题