简体   繁体   中英

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. 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. The cities are numbered 1,2,…,n.

After this, there are m lines describing the flights. Each line has two integers a and b: there is a flight from city a to city 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. Then check if we have visited all nodes. This runs in n^2 though. 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.

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.

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