|
| 1 | +pair<int, int> process(queue<pair<int, int> >& q, vector<int>& visited, unordered_map<int, vector<int> >& x){ |
| 2 | + // Typical BFS with keeping track of the longest distance and farthest element. |
| 3 | + int maxi = INT_MIN, farthest = 0; |
| 4 | + while(!q.empty()){ |
| 5 | + int node = q.front().first; |
| 6 | + int distance = q.front().second; |
| 7 | + q.pop(); |
| 8 | + if(distance > maxi){ |
| 9 | + maxi = distance; |
| 10 | + farthest = node; |
| 11 | + } |
| 12 | + visited[node] = 1; |
| 13 | + for(int i = 0; i < x[node].size(); i++){ |
| 14 | + if(!visited[x[node][i]]){ |
| 15 | + visited[x[node][i]] = 1; |
| 16 | + q.push({x[node][i], distance+1}); |
| 17 | + } |
| 18 | + } |
| 19 | + } |
| 20 | + return {maxi, farthest}; |
| 21 | +} |
| 22 | + |
| 23 | +int Solution::solve(vector<int> &A) { |
| 24 | + // Base Case |
| 25 | + if(A.size() <= 1)return 0; |
| 26 | + |
| 27 | + // Visited array to keep track of visited elements |
| 28 | + vector<int> visited(A.size(), 0); |
| 29 | + |
| 30 | + // Map to make the graph from given array |
| 31 | + unordered_map<int, vector<int> > x; |
| 32 | + x.clear(); |
| 33 | + |
| 34 | + for(int i = 0; i < A.size(); i++){ |
| 35 | + // If the value is -1, it doesn't have any parent. |
| 36 | + // Make the pairs in the adj. list type map |
| 37 | + if( A[i] != -1){ |
| 38 | + x[A[i]].push_back(i); |
| 39 | + x[i].push_back(A[i]); |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + // Start from the first element in the array and mark it visited. |
| 44 | + queue<pair<int, int> > q; |
| 45 | + q.push({0, 0}); |
| 46 | + visited[0] = 1; |
| 47 | + |
| 48 | + // Gets the farthest element from the first element |
| 49 | + int farthest = process(q, visited, x).second; |
| 50 | + |
| 51 | + vector<int> vis(A.size(), 0); |
| 52 | + |
| 53 | + // Now apply BFS on the farthest element found and return the distance |
| 54 | + // of the farthest element found so far. |
| 55 | + q.push({farthest, 0}); |
| 56 | + vis[farthest] = 1; |
| 57 | + return process(q, vis, x).first; |
| 58 | +} |
0 commit comments