We are given a “tree” in the form of a 2D-array, with distinct values for each node.
In the given 2D-array, each element pair [u, v] represents that v is a child of u in the tree.
We can remove exactly one redundant pair in this “tree” to make the result a tree.
You need to find and output such a pair. If there are multiple answers for this question, output the one appearing last in the 2D-array. There is always at least one answer.
Example 1:
1 2 3 4 5 6
Input: [[1,2], [1,3], [2,3]] Output: [2,3] Explanation: Original tree will be like this: 1 / \ 2 - 3
Example 2:
1 2 3 4 5 6
Input: [[1,2], [1,3], [3,1]] Output: [3,1] Explanation: Original tree will be like this: 1 / \\ 2 3
Note:
The size of the input 2D-array will be between 1 and 1000.
Every integer represented in the 2D-array will be between 1 and 2000.
classSolution { boolisTree(vector<vector<int>>& edges, int skip){ vector<vector<int>> graph(2001); unordered_set<int> nodes; for (int i = 0; i < edges.size(); i++) { if (i == skip) continue; graph[edges[i][0]].push_back(edges[i][1]); graph[edges[i][1]].push_back(edges[i][0]); nodes.insert(edges[i][0]); nodes.insert(edges[i][1]); }
unordered_set<int> visited;
vector<int> path; int start = edges[0][0]; if (!dfs(graph, visited, path, start)) returnfalse; return visited.size() == nodes.size(); }
booldfs(vector<vector<int>>& graph, unordered_set<int> &visited, vector<int> &path, int node){ int parent = -1; if (!path.empty()) parent = path.back(); path.push_back(node); visited.insert(node); for (auto n : graph[node]) { if (visited.count(n) && parent != -1 && n != parent) { returnfalse; } elseif (!visited.count(n)) { if (!dfs(graph, visited, path, n)) returnfalse; } } path.pop_back(); returntrue; } public: vector<int> findRedundantConnection(vector<vector<int>>& edges){ vector<int> ans; for (int i = edges.size() - 1; i >= 0; i--) { if (isTree(edges, i)) { ans = edges[i]; break; } } return ans; } };