How to determine if two nodes are connected?

前端 未结 11 1179
清酒与你
清酒与你 2020-12-09 03:31

I\'m concerned that this might be working on an NP-Complete problem. I\'m hoping someone can give me an answer as to whether it is or not. And I\'m looking for more of an an

11条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-09 04:08

    Your description seems to indicate that you are just interested in whether two nodes are connected, not finding the shortest path.

    Finding if two nodes are connected is relatively easy:

    Create two sets of nodes:  toDoSet and doneSet
    Add the source node to the toDoSet 
    while (toDoSet is not empty) {
      Remove the first element from toDoSet
      Add it to doneSet
      foreach (node reachable from the removed node) {
        if (the node equals the destination node) {
           return success
        }
        if (the node is not in doneSet) {
           add it to toDoSet 
        }
      }
    }
    
    return failure.
    

    If you use a hash table or something similar for toDoSet and doneSet, I believe this is a linear algorithm.

    Note that this algorithm is basically the mark portion of mark-and-sweep garbage collection.

提交回复
热议问题