[英]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. 给定使用
HashMap<String, String>
实现的有向图,请确定是否连接了两个节点。
For example: 例如:
"b"--->"a"<---"c"
Map<String, String> graph = new HashMap<>();
map.put("b", "a");
map.put("c", "a");
"b"
and "c"
are connected. "b"
和"c"
已连接。
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"
. 我的问题有所不同,因为即使在
"b"
和"c"
之间没有路径,上述示例中的"b"
和"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. 他们使用了一个
LinkedList<Integer>
数组,该数组将所有相邻节点映射到每个节点。 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. 您可以通过将
value
类的类型更改为Set<String>
而不是String
来进行更改。
Simply reimplement the BFS or DFS with your structure or transform your version to theirs and use their code directly. 只需使用您的结构重新实现BFS或DFS,或将您的版本转换为它们的版本并直接使用其代码。 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:
但请不要害怕,它们很简单,并且在线上有不错的文章,例如Wikipedia:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.