I'm very new to Data structure and algorithm, and we learn graph today, but i don't understand this code, here is it, this code use to find depth of graph:
struct Node {
int id;
int weight;
Node(int id_, int weight_)
{
id = id_;
weight = weight_;
}
};
int depth_tree(vector<Node> graph[], int root)
{
if (graph[root].size() == 0) {
return 0;
} else {
int max_d = depth_tree(graph, graph[root][0].id);
for (int i = 1; i < graph[root].size(); i++) {
int d = depth_tree(graph, graph[root][i].id);
if (d > max_d) {
max_d = d;
}
}
return max_d + 1;
}
}
int main()
{
int n;
cin >> n;
vector<Node> graph[n];
int u, v;
for (int i = 0; i < n - 1; i++) {
cin >> u >> v;
Node temp_uv(v, 0);
graph[u].push_back(temp_uv);
}
cout << depth_tree(graph, 0);
}
i don't understand in 2 point:
FIRST: when calculate depth int max_d = depth_tree(graph, graph[root][0].id i understand it mean it take the id of [0] element of root Node
for example when input
5
0 1
0 2
1 3
3 4
there that max_d would be 1,and 0 must be u when input in main(),but root (root is u not change value) so i think when call depth_tree(graph, 0) just to find deep of 0???????
SECOND:why int max_d = depth_tree(graph, graph[root][0].id)??? like above example there are 1 2 3 4??? so answer is should be 4(wrong but i don't understand)
ANYONE PLEASE EXPLAIN THIS CODE LOGIC, THANKS A LOTS, i'm very curious