Skip to content

Instantly share code, notes, and snippets.

@s4553711
Created May 3, 2018 15:22
Show Gist options
  • Save s4553711/8a58b576bced6e1aa3a39c30428778df to your computer and use it in GitHub Desktop.
Save s4553711/8a58b576bced6e1aa3a39c30428778df to your computer and use it in GitHub Desktop.
class Solution {
public:
vector<int> findRedundantConnection(vector<vector<int>>& edges) {
unordered_map<int, vector<int>> graph;
for(const auto& edge: edges) {
int u = edge[0];
int v = edge[1];
unordered_set<int> visited;
if (hashPath(u, v, graph, visited)) return edge;
graph[u].push_back(v);
graph[v].push_back(u);
}
return {};
}
private:
bool hashPath(int curr, int goal, const unordered_map<int, vector<int>>& graph, unordered_set<int>& visited) {
if (curr == goal) return true;
visited.insert(curr);
if (!graph.count(curr) || !graph.count(goal)) return false;
for(int next: graph.at(curr)) {
if (visited.count(next)) continue;
if (hashPath(next, goal, graph, visited)) return true;
}
return false;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment