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 relation, find the degrees of two people, return -1 if they can not be 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 = 4 return 2

Gien a graph:

1      2-----4
             /
           /
          3
{1#2,4#3,4#4,2,3} and s = 1, t = 4 return -1
import java.util.*;

public class SixDegrees {
    class UndirectedGraphNode {
        int label;
        List<UndirectedGraphNode> neighbors;
        UndirectedGraphNode(int x) {
            label = x;
            neighbors = new ArrayList<UndirectedGraphNode>();
        }
    }

     public int sixDegrees(List<UndirectedGraphNode> graph, UndirectedGraphNode s, UndirectedGraphNode t) {
        if (graph.size() == 0 || !graph.contains(s)) return -1;
         Queue<UndirectedGraphNode> queue = new LinkedList<>();
         Set<UndirectedGraphNode> visited = new HashSet<UndirectedGraphNode>();

         queue.add(s);
         visited.add(s);
         int count = 0;
         while (!queue.isEmpty()) {
             int size = queue.size();
             for (int i = 0 ; i < size; i++) {
                 UndirectedGraphNode cur = queue.poll();
                 if (cur.equals(t)) {
                     return count;
                 } else {
                     for (UndirectedGraphNode neighbor: cur.neighbors) {
                         if (!visited.contains(neighbor)) {
                             queue.offer(neighbor);
                             visited.add(neighbor);
                         }
                     }
                 }

             }
             count++;
         }
         return -1;
     }
}

results matching ""

    No results matching ""