Six Degrees (Ladder)
Description
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
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
Link
Method
- x
- x
Example
- 1
/** * Definition for undirected graph. * struct UndirectedGraphNode { * int label; * vector<UndirectedGraphNode *> neighbors; * UndirectedGraphNode(int x) : label(x) {}; * }; */ class Solution { public: /** * @param graph a list of Undirected graph node * @param s, t two Undirected graph nodes * @return an integer */ int sixDegrees(vector<UndirectedGraphNode*> graph, UndirectedGraphNode* s, UndirectedGraphNode* t) { // Write your code here if (!s || !t) { return -1; } if (s == t) { return 0; } // bfs int depth = 1; int count = 1; queue<UndirectedGraphNode*> q; unordered_set<UndirectedGraphNode*> used; q.push(s); used.insert(s); while (!q.empty()) { auto cur = q.front(); q.pop(); --count; for (auto& neighbor : cur->neighbors) { if (used.find(neighbor) != used.end()) { continue; } if (neighbor == t) { return depth; } q.push(neighbor); used.insert(neighbor); } if (count == 0) { depth++; count = q.size(); } } return -1; } };
Similar problems
x
Tags
x