Skip to the code
cf.
+10 XP

#416 Can Two Devices Talk?

easy

A home network has n devices numbered 0 to n - 1. Each links[i] = [a, b] is a cable between a and b, and data can go either way along it.

Write canTalk(n, links, from, to) that returns true if data can travel from device from to device to through any chain of cables, and false otherwise. A device can always talk to itself.

Example 1

Input: n = 5, links = [[0,1],[1,2],[3,4]], from = 0, to = 2
Output: true

0 reaches 1, and 1 reaches 2.

Example 2

Input: n = 5, links = [[0,1],[1,2],[3,4]], from = 0, to = 4
Output: false

Devices 3 and 4 are only connected to each other.

Constraints

  • 1 <= n <= 100000
  • 0 <= links.length <= 100000
  • 0 <= a, b, from, to < n
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).