Given a social network, a start person, and an end person, find the minimum number of steps from person A to person B.
Example:
1 -> 2 -> 5
| | |
| | |
| | |
v v v
4 <- 3
Queries:
1, 5: 2
3, 1: 2
5, 3: -1
这题本质上是在社交网络图中求两个人之间的最短路径长度:把每个人看成图的节点,关注关系或连接关系看成边,然后从起点出发,使用 BFS 按层扩展,第一次到达终点时对应的步数就是最少步数。如果图是有向图,就只能沿着方向走;如果不存在路径,则返回 -1。这个题通常考察图建模、最短路思维以及 BFS 的基础应用。
正文完