Six Degrees
- Lintcode : 531 / Leetcode :
- Level : Medium
Problem
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
Concept & Algorithm
Time Complexity & Space Complexity
time : O(nodes * avg neighbors)
space: O(nodes)
Answer
/**
* Definition for undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution {
public:
int sixDegrees(vector<UndirectedGraphNode*> graph, UndirectedGraphNode* s, UndirectedGraphNode* t) {
map<UndirectedGraphNode*, int> degree;
queue<UndirectedGraphNode*> q;
q.push(s);
degree[s] = 0;
while (!q.empty()) {
UndirectedGraphNode* n = q.front(); q.pop();
if (n == t) return degree[t];
for (auto j : n -> neighbors) {
if (degree[j] != 0 && degree[j] <= degree[n] + 1) continue;
degree[j] = degree[n] + 1;
q.push(j);
}
}
return -1;
}
};
沒有留言:
張貼留言