How to determine if two nodes are connected?

前端 未结 11 1184
清酒与你
清酒与你 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:19

    If all you need is to determine if 2 nodes are connected you can use sets instead, which is faster than graph algorithms.

    1. Split your entire graph into edges. Add each edge to a set.
    2. On next iteration, draw edges between the 2 outer nodes of the edge you made in step 2. This means adding new nodes (with their corresponding sets) to the set the original edge was from. (basically set merging)
    3. Repeat 2 until the 2 nodes you're looking for are in the same set. You will also need to do a check after step 1 (just in case the 2 nodes are adjacent).

    At first your nodes will be each in its set,

    o   o1   o   o   o   o   o   o2
     \ /     \ /     \ /     \ /
     o o     o o     o o     o o
       \     /         \     /
       o o o o         o o o o 
          \               /
           o o1 o o o o o o2
    

    As the algorithm progresses and merges the sets, it relatively halves the input.

    In the example above I was looking to see if there was a path between o1 and o2. I found this path only at the end after merging all edges. Some graphs may have separate components (disconnected) which entails that you will not be able to have one set at the end. In such a case you can use this algorithm to test for connectedness and even count the number of components in a graph. The number of components is the number of sets you are able to get when the algorithm finishes.

    A possible graph (for the tree above):

    o-o1-o-o-o2
      |    |
      o    o
           |
           o
    

提交回复
热议问题