Passing news by DM
Write code · Medium · §9.3 Nearest first
There are n users on a social network, numbered from 0 to n - 1. A record [a, b] in follows means that a follows b. On this social network, you can send a DM only to people you follow.
Person start wants to pass some news to person target. Anyone who receives the news by DM can pass it on by DM. Complete the function solution, which returns the smallest number of DMs that must be sent for the news to reach target. If the news cannot reach target, return -1.
Function
solution(n, follows, start, target)
Constraints
nis an integer from 2 to 100,000.- The length of
followsis from 1 to 100,000. - Each element of
followshas the form[a, b], whereaandbare different integers from 0 ton - 1. The same record never appears twice. startandtargetare different integers from 0 ton - 1.
Examples
| n | follows | start | target | result |
|---|---|---|---|---|
5 | [[0, 4], [4, 3], [0, 1], [1, 2], [2, 3]] | 0 | 3 | 2 |
5 | [[0, 1], [1, 2], [3, 0], [3, 4], [2, 4]] | 0 | 4 | 3 |
Starter code
def solution(n, follows, start, target):
answer = 0
return answerSolve this problem in your browser
Python runs in your browser and checks your answer right away. Hints and the answer are on the problem page.