美文网首页
531. Six Degrees

531. Six Degrees

作者: 鸭蛋蛋_8441 | 来源:发表于2019-08-15 07:17 被阅读0次

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

      本文链接:https://www.haomeiwen.com/subject/esfajctx.html