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):
/**
* 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