Problem 566793 · easy · Level 05 Advanced Algorithms & Graphs

Connected If You Ignore the Arrows

graphs · directed graph · weak connectivity

A directed graph is weakly connected when the undirected graph you get by forgetting every arrow's direction is connected: any node can be reached from any other if you are allowed to travel the wrong way down an edge.

Write weakly_connected(n, edges) returning True or False.

Examples

Input:  n = 3, edges = [(0, 1), (2, 1)]
Output: True
Explanation: nobody can leave node 1, but ignoring the arrows all three hang together.

Input:  n = 3, edges = [(0, 1)]
Output: False
Explanation: node 2 is on its own.

Constraints

  • 1 <= n <= 2 * 10**4, 0 <= len(edges) <= 10**5

Goals

  • Tell the directed graph apart from its underlying undirected one
  • Decide weak connectivity with a single search
  • See that one-way streets can hide an otherwise connected map
Starting Python…