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
Example1
Input: {1,2,3#2,1,4#3,1,4#4,2,3} and s = 1, t = 4
Output: 2
Explanation:
1------2-----4
\ /
\ /
\--3--/
Example2
Input: {1#2,4#3,4#4,2,3} and s = 1, t = 4
Output: -1
Explanation:
1 2-----4
/
/
3
Code (Java):1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | /** * Definition for Undirected graph. * class UndirectedGraphNode { * int label; * List<UndirectedGraphNode> neighbors; * UndirectedGraphNode(int x) { * label = x; * neighbors = new ArrayList<UndirectedGraphNode>(); * } * }; */ public class Solution { /* * @param graph: a list of Undirected graph node * @param s: Undirected graph node * @param t: Undirected graph nodes * @return: an integer */ public int sixDegrees(List<UndirectedGraphNode> graph, UndirectedGraphNode s, UndirectedGraphNode t) { // write your code here if (graph == null || graph.size() == 0 ) { return 0 ; } // build the graph // Map<UndirectedGraphNode, List<UndirectedGraphNode>> adjList = new HashMap<>(); for (UndirectedGraphNode node : graph) { adjList.put(node, node.neighbors); } int len = 0 ; Queue<UndirectedGraphNode> queue = new LinkedList<>(); Set<UndirectedGraphNode> visited = new HashSet<>(); queue.offer(s); visited.add(s); while (!queue.isEmpty()) { int size = queue.size(); for ( int i = 0 ; i < size; i++) { UndirectedGraphNode curNode = queue.poll(); if (curNode == t) { return len; } for (UndirectedGraphNode neighbor : adjList.get(curNode)) { if (!visited.contains(neighbor)) { queue.offer(neighbor); visited.add(neighbor); } } } len += 1 ; } return - 1 ; } } |
Why to create adjList when given input itself is graph?
ReplyDeletein the line 49, we can simply say curNode.neighbors