Six Degrees

Question

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

Given a graph:

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

Given a graph:

{1#2,4#3,4#4,2,3} and s = 1, t = 4 return -1

Solution:

这个是类似于求多少了level, 多少度,而不是列出具体的方案,所以可以考虑使用BFS。d[y] = d[x] + 1

下面是参考了九张算法的方案:

# Definition for Undirected graph node
# class UndirectedGraphNode:
#     def __init__(self, x):
#         self.label = x
#         self.neighbors = []

import Queue

class Solution:
    '''
    @param {UndirectedGraphNode[]} graph a list of Undirected graph node
    @param {UndirectedGraphNode} s, t two Undirected graph nodes
    @return {int} an integer
    '''
    def sixDegrees(self, graph, s, t):
        # Write your code here
        d = {}
        q = Queue.Queue(maxsize = len(graph))

        q.put(s)
        d[s] = 0
        while not q.empty():
            x = q.get()
            if x == t:
                return d[x]

            for y in x.neighbors:
                if y not in d:
                    d[y] = d[x] + 1
                    q.put(y)

        return -1

Last updated

Was this helpful?