问题
I have an adjacency list representation of a graph but it is not symmetric i.e,. if a node A
has an edge to B
, it is not true that B
has an edge with A
. I guess this will be a directional graph (digraph).
What is a good way to detect all the bidirectional paths from a node. I know I can use DFS to detect the paths from a node to another nodes of the graph. I guess what I am looking for is a bidirectional DFS where only the bidirectional edges are taken into account.
So one way to do that is to look at the neighbour for a node and figure out if this is a bidirectional relationship. However, for this I will need to go through all the immediate connections of this neighbouring node and see if the first node is also a connection and if yes, to continue with the recursion. I wonder if this is an efficient way to do this?
回答1:
With a fairly standard "adjacency set" representation, where you use some sort of set data structure (hash- or tree-based) instead of lists to represent the edges coming out of a node, you can just query whether the reversed version of an edge exists in the graph. Building an adjacency set representation from an adjacency list representation is straightfoward.
Alternatively, you can build one set of all the edges in the graph and then filter edges out of the graph whose reversed version isn't in the set. This can be more convenient if you wouldn't have any further use for the adjacency set representation after using it in the other approach. If you want to keep memory usage down, you can remove edges from the set while building it if you find their reversed version in the graph, and then remove edges from the graph afterward if they're in the set instead of if their reversed version isn't.
来源:https://stackoverflow.com/questions/43553273/detecting-mutual-edges-in-a-graph