Six Degrees

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-1if they can not been connected by friends of friends.

Example

Gien a graph:

1------2-----4
 \          /
  \        /
   \--3--/

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

Gien a graph:

1      2-----4
             /
           /
          3

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

Solution: Find shortest path. BFS.

public int sixDegrees(List<UndirectedGraphNode> graph,
                          UndirectedGraphNode s,
                          UndirectedGraphNode t) {
    if(graph == null || graph.size() == 0) {
        return -1;
    }            
    if(s.equals(t)) {
        return 0;
    }
    Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
    HashSet<UndirectedGraphNode> set = new HashSet<UndirectedGraphNode>();
    int level = 0, cur = 1, next = 0;
    queue.add(s);
    set.add(s);
    while(!queue.isEmpty()) {
        UndirectedGraphNode tmp = queue.poll();
        cur--;
        for(UndirectedGraphNode n : tmp.neighbors) {
            if(n.equals(t)) {
                return level + 1;
            }
            if(!set.contains(n)) {
                queue.add(n);
                set.add(n);
                next++;
            }
        }
        if(cur == 0) {
            cur = next;
            next = 0;
            level++;
        }
    }
    return -1;        
}

results matching ""

    No results matching ""