class Solution {
public:
int dfs(vector<vector<int>>& graph, vector<vector<int>>& graphw, int signalSpeed, int a, int fa, int ws) {//单项递归
int cnt = ws % signalSpeed == 0;
for (int i = 0; i < graph[a].size(); i++) {
int next = graph[a][i];
if (next != fa) {//父节点和子节点不同,导致单向。
cnt += dfs(graph, graphw, signalSpeed, next, a, ws + graphw[a][next]);
}
}
return cnt;
}
vector<int> countPairsOfConnectableServers(vector<vector<int>>& edges, int signalSpeed) {
int size = edges.size()+1;
vector<vector<int>> graphw(size, vector<int>(size, 0));
vector<vector<int>> graphto(size);
for (int i = 0; i < size-1; i++) {
int a = edges[i][0];
int b = edges[i][1];
int w = edges[i][2];
graphw[a][b] = w;
graphw[b][a] = w;
graphto[a].push_back(b);
graphto[b].push_back(a);
}//这里可以写成一个pair
vector<int> result(size, 0);
for (int root = 0; root < size; root++) {
int s = 0;
for (int i = 0; i < graphto[root].size(); i++) {
int next = graphto[root][i];
int t = dfs(graphto, graphw, signalSpeed, next, root, graphw[next][root]);
result[root] += s * t;
s += t;
}
}
return result;
}
};
注意创建递归时,递归初始化应该放在for之外,否则会改变递归的值:
把cur放在里面,导致cur的return是for每次初始化。
利用used实现:
class Solution {
public:
int dfs(vector<vector<int>>& graph, int x, vector<int>& used, int curv, vector<vector<int>>& graphw, int signalSpeed) {//回溯递归 used标记是否经历过
int cur= curv % signalSpeed == 0;
for (int i = 0; i < graph[x].size(); i++) { // 遍历节点n链接的所有节点
int next = graph[x][i];
if (used[next] == 1) continue;
curv += graphw[x][next];
used[next] = 1;
cur+= dfs(graph, next, used, curv, graphw, signalSpeed);
curv-= graphw[x][next];
used[next] = 0;
}
return cur;
}
vector<int> countPairsOfConnectableServers(vector<vector<int>>& edges, int signalSpeed) {
int size = edges.size() + 1;
vector<vector<int>> graphw(size, vector<int>(size, 0));
vector<vector<int>> graphto(size);
for (int i = 0; i < edges.size(); i++) {
int a = edges[i][0];
int b = edges[i][1];
int w = edges[i][2];
graphw[a][b] = w;
graphw[b][a] = w;
graphto[a].push_back(b);
graphto[b].push_back(a);
}
vector<int> result(size, 0);
for (int root = 0; root < size; root++) {
vector<int> used(size, 0);
used[root] = 1;
int s = 0;
for (int i = 0; i < graphto[root].size(); i++) {
int next = graphto[root][i];
used[next] = 1;
int cur = 0;
cur += dfs(graphto, next, used, graphw[next][root], graphw, signalSpeed);
result[root] += s*cur;
s += cur;
}
}
return result;
}
};