Approach
Breadth-first search
For Pythagorean Distance Nodes in a Tree, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 47 lines of C++ from the credited upstream file pythagorean-distance-nodes-in-a-tree.cpp.
- The implementation visibly relies on sequence storage.
- 5 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution {6public:7 int specialNodes(int n, vector<vector<int>>& edges, int x, int y, int z) {8 vector<vector<int>> adj(n);9 const auto& bfs = [&](int u) {10 vector<int> dist(n, -1);11 dist[u] = 0;12 vector<int> q = {u};13 while (!empty(q)) {14 vector<int> new_q;15 for (const auto& u : q) {16 for (const auto& v : adj[u]) {17 if (dist[v] != -1) {18 continue;19 }20 dist[v] = dist[u] + 1;21 new_q.emplace_back(v);22 }23 }24 q = move(new_q);25 }26 return dist;27 };28 29 for (const auto& e : edges) {30 adj[e[0]].emplace_back(e[1]);31 adj[e[1]].emplace_back(e[0]);32 }33 const auto& dist1 = bfs(x);34 const auto& dist2 = bfs(y);35 const auto& dist3 = bfs(z);36 int result = 0;37 for (int u = 0; u < n; ++u) {38 const int64_t a = dist1[u], b = dist2[u], c = dist3[u];39 const auto& mx = max({a, b, c});40 if (a * a + b * b + c * c == 2 * mx * mx) {41 ++result;42 }43 }44 return result;45 }46};47