Skip to content
BytePatterns

Reachable Pair Check

EasyUnion-Find#union-find#connectivity~15m

Problem

A network has n nodes numbered 0 to n minus 1 and a list of two-way links between pairs of nodes. Given a source node and a target node, decide whether some chain of links leads from one to the other. A node always reaches itself.

Examples

Input:  n = 3, links = [[0, 1], [1, 2], [2, 0]], source = 0, target = 2
Output: True
Input:  n = 6, links = [[0, 1], [0, 2], [3, 5], [5, 4], [4, 3]], source = 0, target = 5
Output: False
Why:    the links form two separate groups, {0, 1, 2} and {3, 4, 5}
Input:  n = 1, links = [], source = 0, target = 0
Output: True
Why:    edge case, a node reaches itself without any link

Hints

0 / 3

Stuck on the idea rather than the code? Disjoint Sets Basics covers it.