531. Six Degrees

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存储层次关系。

代码:

笨的方法


聪明的方法:


你可能感兴趣的:(531. Six Degrees)