简体   繁体   English

查找有向图中是否连接了两个节点

[英]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.

相关问题 给定一个有向图,找出两个节点之间是否存在路由 - Given a directed graph, find out whether there is a route between two nodes java使用JUNG在有向图中查找连通分量 - java find connected components in Directed Graph using JUNG 如何使用Java查找图的中心(顶点,该顶点与其他每个顶点相连,但边指向图的中心) - how to Find the center of graph (vertex, that is connected with every other vertex, but edges are directed to the center of graph) with java 在图中编码连接的节点 - coding connected nodes in graph 使用快速查找算法(Java)查找定向图中所有弱连通分量的优化 - Optimization for Find All Weakly Connected Components in Directed Graph Using Quick-Find Algorithm (Java) 如何在不遍历所有图(有向图)的情况下找到通向节点A的节点 - How to find the nodes that leads to node A without traversing all the graph (directed graph) 如何在有向图中找到凹坑? - how to find a pit in a directed graph? 查找两个节点之间的隐藏节点-图形-Java - Find the hidden nodes between two nodes - graph - java Java,在有向图中连接边,以便图可遍历 - Java, connected edges in a directed graph so that the graph is traversable 在图中查找“连接的组件” - Find 'connected components' in graph
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM