简体   繁体   English

如何检查图中的所有节点是否可以从所有其他节点访问?

[英]How to check if all nodes in a graph are reachable from all other nodes?

I am trying to solve this question:我正在尝试解决这个问题:

There are n cities and m flight connections.有 n 个城市和 m 个航班连接。 Your task is to check if you can travel from any city to any other city using the available flights.您的任务是检查您是否可以使用可用航班从任何城市前往任何其他城市。

Input输入

The first input line has two integers n and m: the number of cities and flights.第一个输入行有两个整数 n 和 m:城市和航班的数量。 The cities are numbered 1,2,…,n.城市编号为 1,2,...,n。

After this, there are m lines describing the flights.在此之后,有 m 行描述航班。 Each line has two integers a and b: there is a flight from city a to city b.每行有两个整数 a 和 b:有一个从城市 a 到城市 b 的航班。 All flights are one-way flights.所有航班均为单程航班。

My approach is to do a dfs rooted at every node, keep track of all nodes we've visited.我的方法是在每个节点上做一个 dfs,跟踪我们访问过的所有节点。 Then check if we have visited all nodes.然后检查我们是否访问了所有节点。 This runs in n^2 though.不过,这在 n^2 中运行。 This times out though.这虽然超时。

Could someone guide me through a more optiomal algorithm?有人可以指导我通过更优化的算法吗?

Your criterion that every node is reachable from every other node is equivalent to testing whether the number of strongly connected components in the graph is 1.你的每个节点都可以从其他每个节点到达的标准相当于测试图中的强连通分量的数量是否为 1。

There are efficient well-known algorithms for finding the strongly connected components of a graph, such as Kosaraju's algorithm and Tarjan's strongly connected components algorithm , which both run in O( n + m ) time on a graph with n nodes and m edges.有一些众所周知的高效算法可用于查找图的强连通分量,例如Kosaraju 算法Tarjan 强连通分量算法,它们都在具有n 个节点和m 条边的图上以 O( n + m ) 时间运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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