简体   繁体   中英

Find if two nodes are connected in a directed graph

Given a directed graph implemented using HashMap<String, String> , find if two nodes are connected.

For example:

"b"--->"a"<---"c"

Map<String, String> graph = new HashMap<>();
map.put("b", "a");
map.put("c", "a");

"b" and "c" are connected.

I found a post in which the graph is a directed graph but the solution is to find if there is a path between two nodes. My question is different because "b" and "c" in above example are considered connected even though there is no path between "b" and "c" .

There is no real difference between your representation and the one used in the link you provided. They used an array of LinkedList<Integer> which maps to each node all adjacent nodes. You also have this information, every key of your map is linked to all adjacent nodes.

But first note that your representation is very restricted. You restrict a node to have only one neighboor. You can change this by changing the type of the value class to Set<String> instead of String for example.

Simply reimplement the BFS or DFS with your structure or transform your version to theirs and use their code directly. However the first solution will be faster but requires you to understand how those searches work. But do not be afraid, they are easy and there are good articles online, for example at Wikipedia:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM