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

Example:

Given a graph:

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

{1,2,3#2,1,4#3,1,4#4,2,3} and s = 1, t = 4 return 2, where # is used to spearate different node.

Solution:

Breadth first search from s to t, extension from tree level traversal.

Code:

public class Solution {

    public int sixDegrees(List<UndirectedGraphNode> graph,
                          UndirectedGraphNode s,
                          UndirectedGraphNode t) {
        if (graph == null) {
            return -1;
        }
        Queue<UndirectedGraphNode> q = new LinkedList<>();
        HashSet<UndirectedGraphNode> visited = new HashSet<>();
        q.add(s);
        visited.add(s);
        int count = 0;
        while (!q.isEmpty()) {
            int size = q.size();
            for (int i = 0; i < size; i++) {
                UndirectedGraphNode node = q.poll();
                if (node.label == t.label) {
                    return count;
                }
                for (UndirectedGraphNode x : node.neighbors) {
                    if (!visited.contains(x)) {
                        q.add(x);
                        visited.add(x);
                    }
                }
            }
            count++;
        }
        return -1;
    }
}

results matching ""

    No results matching ""