Reputation: 4898
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"
.
Upvotes: 0
Views: 1474
Reputation: 25903
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:
Upvotes: 0