531. Six Degrees

2019-08-15  本文已影响0人  鸭蛋蛋_8441

Description

Six degrees of separation is the theory that everyone and everything is six or fewer steps away, by way of introduction, from any other person in the world, so that a chain of "a friend of a friend" statements can be made to connect any two people in a maximum of six steps.

Given a friendship relations, find the degrees of two people, return -1 if they can not been connected by friends of friends.

Example

Example1

Input: {1,2,3#2,1,4#3,1,4#4,2,3} and s = 1, t = 4

Output: 2

Explanation:

    1------2-----4

    \          /

      \        /

      \--3--/

Example2

Input: {1#2,4#3,4#4,2,3} and s = 1, t = 4

Output: -1

Explanation:

    1      2-----4

                /

              /

              3

思路:

还是BFS,不过有分层的概念,如果不分层会把不在路径里的点的遍历也计算进去,比较笨的方法就是分层BFS,然后数degree,比较聪明的方式是用hashmap存储层次关系。

代码:

笨的方法

聪明的方法:

上一篇 下一篇

猜你喜欢

热点阅读