Six Degrees

LintCode-531.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

Given a graph:

1      2-----4
             /
           /
          3

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

/**
 * Definition for Undirected graph.
 * class UndirectedGraphNode {
 *     int label;
 *     List<UndirectedGraphNode> neighbors;
 *     UndirectedGraphNode(int x) { 
 *         label = x;
 *         neighbors = new ArrayList<UndirectedGraphNode>(); 
 *     }
 * };
 */
public class Solution {
    private int degree = 0;
    
    /**
     * @param graph a list of Undirected graph node
     * @param s, t two Undirected graph nodes
     * @return an integer
     */
    public int sixDegrees(List<UndirectedGraphNode> graph,
                          UndirectedGraphNode s,
                          UndirectedGraphNode t) {
        if (graph == null || graph.size() == 0 || s == t) {
            return 0;
        }
        
        Map<UndirectedGraphNode, Integer> map = new HashMap<>();
        map.put(s, 0);
        
        Queue<UndirectedGraphNode> queue = new LinkedList<>();
        queue.offer(s);
        
        while (!queue.isEmpty()) {
            UndirectedGraphNode node = queue.poll();
            int degree = map.get(node);
            
            for (UndirectedGraphNode n : node.neighbors) {
                if (!map.containsKey(n)) {
                    map.put(n, degree + 1);
                    queue.offer(n);
                    
                    if (n == t) {
                        return degree + 1;
                    }
                }
            }
        }
        
        return -1;
    }
}

Hope this helps,
Michael

DigitalOcean Referral Badge