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

代码:

笨的方法


聪明的方法:


©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,505评论 0 10
  • The Inner Game of Tennis W Timothy Gallwey Jonathan Cape ...
    网事_79a3阅读 12,456评论 3 20
  • 原题 六度分离是一个哲学问题,说的是每个人每个东西可以通过六步或者更少的步数建立联系。现在给你一个友谊关系,查询两...
    Jason_Yuan阅读 904评论 0 0
  • 19.6.18好事第165天 1.今天神父的课讲的太例外了,打破了我们惯有的思维方式,太有深度了。 2.和姐妹一起...
    伯铎_4431阅读 89评论 0 0
  • 2017年五一节,往年如果不是值班,就是在家睡觉,今年工作上有了些许变化,不再有假期,每天都得去公司忙碌,毕竟手底...
    忘了_阅读 226评论 0 0