Skip to content

Instantly share code, notes, and snippets.

@KSoto
Last active September 29, 2022 19:36
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KSoto/15f4069457be29f3da2e803c192d75ae to your computer and use it in GitHub Desktop.
Save KSoto/15f4069457be29f3da2e803c192d75ae to your computer and use it in GitHub Desktop.
Find the longest path between any two pairs of vertices in a graph
/*
We are given a map of cities connected with each other via cable lines such that there is no cycle between any two cities. We need to find the maximum length of cable between any two cities for given city map.
Input : n = 6
1 2 3 // Cable length from 1 to 2 (or 2 to 1) is 3
2 3 4
2 6 2
6 4 6
6 5 5
Output: maximum length of cable = 12
*/
class Node {
constructor(node_name, weight, currentSum) {
this.node_name = node_name;
this.weight = weight;
this.currentSum = currentSum;
}
}
class Graph {
constructor(num_nodes) {
// this.adjacencyList looks like this: "[[],[],[],[],[],[]]"
this.adjacencyList = Array.from({length: num_nodes}, e => Array());
this.num_nodes = num_nodes;
}
addEdge(x,y,weight) {
this.adjacencyList[x].push(new Node(y, weight, 0));
this.adjacencyList[y].push(new Node(x, weight, 0));
return this.adjacencyList;
}
longest_path_between_any_pair() {
var max_sum=0;
for(var i=0; i<this.num_nodes; i++) {
var visited = new Array(this.num_nodes).fill(false);
var stack = [];
if(this.adjacencyList[i].length==0)
continue;
stack.push(new Node(i, 0, 0));
while(stack.length>0) {
var curr = stack.pop();
if(visited[curr.node_name]==true)
continue;
visited[curr.node_name]=true;
if(curr.currentSum>max_sum)
max_sum=curr.currentSum;
for(var neighbor=0; neighbor<this.adjacencyList[curr.node_name].length; neighbor++) {
stack.push(new Node(this.adjacencyList[curr.node_name][neighbor].node_name,
this.adjacencyList[curr.node_name][neighbor].weight,
curr.currentSum + this.adjacencyList[curr.node_name][neighbor].weight));
}
}
}
return max_sum;
}
}
var g = new Graph(7); //7 because we aren't starting at 0. So we need x[1],...x[6]
g.addEdge(1,2,3);
g.addEdge(2,3,4);
g.addEdge(2,6,2);
g.addEdge(6,4,6);
g.addEdge(6,5,5);
g.longest_path_between_any_pair();
// adjacencyList looks like this:
/*
[
[],
[{"neighbor":2,"weight":3,"path_sum":0}],
[{"neighbor":1,"weight":3,"path_sum":0},{"neighbor":3,"weight":4,"path_sum":0},{"neighbor":6,"weight":2,"path_sum":0}],
[{"neighbor":2,"weight":4,"path_sum":0}],
[{"neighbor":6,"weight":6,"path_sum":0}],
[{"neighbor":6,"weight":5,"path_sum":0}],
[{"neighbor":2,"weight":2,"path_sum":0},{"neighbor":4,"weight":6,"path_sum":0},{"neighbor":5,"weight":5,"path_sum":0}]
]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment