void longestPath(int root, int father) { if(father != -1) { printf("%d %d\n", root, father); dist[root][father] = dist[father][root] = 1; for (int i = 0; i < treeNodes; ++i) { if(i != root && dist[i][father] != -1) { dist[i][root] = dist[i][father] + 1; dist[root][i] = dist[i][root]; } } } if (tree[root].m_pLeft) longestPath(tree[root].m_pLeft->id, root); if (tree[root].m_pRight) longestPath(tree[root].m_pRight->id, root); }
// Driver program to test above functions int main() { // Create a GraphL given in the above diagram. Here vertex numbers are // 0, 1, 2, 3, 4, 5 with following mappings: // 0=r, 1=s, 2=t, 3=x, 4=y, 5=z Graphm g(6); g.setEdge(0, 1, 5); g.setEdge(0, 2, 3); g.setEdge(1, 3, 6); g.setEdge(1, 2, 2); g.setEdge(2, 4, 4); g.setEdge(2, 5, 2); g.setEdge(2, 3, 7); g.setEdge(3, 5, 1); // 0 1 2 3 4 5 // g.setEdge(3, 4, 9); // INF 0 2 9 18 23 // g.setEdge(4, 5, 5); // INF 0 2 9 18 23 /* dist[0]: INF dist[1]: 0 dist[2]: 2 dist[3]: 9 dist[4]: 18 dist[5]: 23 There is not path from src:1 to dest:0 There is not path from src:1 to dest:1 The longest distance from src:1 to dest:2 is 2, with the following path: 1 2 The longest distance from src:1 to dest:3 is 9, with the following path: 1 2 3 The longest distance from src:1 to dest:4 is 18, with the following path: 1 2 3 4 The longest distance from src:1 to dest:5 is 23, with the following path: 1 2 3 4 5 */ // 0 1 2 3 4 5 g.setEdge(3, 4, -1); // INF 0 2 9 8 10 note: continuous call set same edge causes error g.setEdge(4, 5, -2); // INF 0 2 9 8 10 /* dist[0]: INF dist[1]: 0 dist[2]: 2 dist[3]: 9 dist[4]: 8 dist[5]: 10 There is not path from src:1 to dest:0 There is not path from src:1 to dest:1 The longest distance from src:1 to dest:2 is 2, with the following path: 1 2 The longest distance from src:1 to dest:3 is 9, with the following path: 1 2 3 The longest distance from src:1 to dest:4 is 8, with the following path: 1 2 3 4 The longest distance from src:1 to dest:5 is 10, with the following path: 1 2 3 5 */ int s = 1; int d = 5; cout << "Following are longest distances from source vertex " << s << " \n"; longestPath(&g, s, d); cout << endl; return 0; }
int longestPath(int src, int dest) { if(src == dest) return 0; if(maxDist[src][dest] != -1) return maxPath[src][dest]; best = -INF; for(i=0; i< graph[src].size(); i++) { int v = graph[src][i]; int temp = length[src][i] + longestPath(v, dest); if(temp > best) best = temp; } maxPath[src][dest] = best; return best; }
void searchPath(int root) { for (int i = 0; i < treeNodes; ++i) { for (int j = 0; j < treeNodes; ++j) { dist[i][j] = -1; dist[j][i] = -1; } } for (int i = 0; i < treeNodes; ++i) dist[i][i] = 0; longestPath(treeRoot, -1); for (int i = 0; i < treeNodes; ++i) { for (int j = 0; j < treeNodes; ++j) printf("%d ", dist[i][j]); printf("\n"); } }