Problem: 1466. 重新规划路线
思路
这道题就是遍历一个树,特殊在于树的节点之间多了方向。
假设到节点 0 的路线方向为正,那么只需要把书上所有逆向路线改为正,即统计有向树上的逆向边条数。
解题方法
- 采用邻接表构建树,并在节点域追加记录当前路线终点;
- 深度遍历树,找出逆边并统计。
复杂度
时间复杂度: O ( n ) O(n) O(n)
空间复杂度: O ( n ) O(n) O(n)
Code
class Solution {
public:
int ans = 0;
void DFS(vector<vector<vector<int>>> &vertex, int curr, int parent) {
for (auto ver: vertex[curr]) {
if (ver[0] == parent) continue;
if (curr != ver[1]) ans++;
DFS(vertex, ver[0], curr);
}
}
int minReorder(int n, vector<vector<int>>& connections) {
vector<vector<vector<int>>> vertex(n);
for (auto connection: connections) {
vertex[connection[0]].push_back({connection[1], connection[1]});
vertex[connection[1]].push_back({connection[0], connection[1]});
}
DFS(vertex, 0, -1);
return ans;
}
};