DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on

Shortest Path In DAG

class shortestPathInDAG {
  constructor(v) {
    this.V = v;
    this.adjL = [];
    for (let i = 0; i < v; i++) {
      this.adjL[i] = [];
    }
    this.indegree = [];
    for (let i = 0; i < v; i++) {
      this.indegree[i] = 0;
    }
    this.topOrder = [];
  }

  addEdge = (source, destination, weight) => {
    this.adjL[source].push({ d: destination, wt: weight });
  };
  printAdjList = () => {
    console.log(this.adjL);
  };

  getIndrgree = () => {
    for (let i = 0; i < this.V; i++) {
      let current = this.adjL[i];
      for (let j = 0; j < current.length; j++) {
        this.indegree[current[j].d]++;
      }
    }
  };

  getTopologicalSort = () => {
    let q = [];
    this.getIndrgree();
    for (let i = 0; i < this.V; i++) {
      if (this.indegree[i] == 0) q.push(i);
    }

    let cnt = 0;

    while (q.length) {
      let u = q.shift();
      this.topOrder.push(u);
      this.adjL[u].forEach((adjacent, i) => {
        this.indegree[adjacent?.d]--;
        if (this.indegree[adjacent?.d] === 0) {
          q.push(adjacent?.d);
        }
      });
      cnt++;
    }

    // for (let i = 0; i < this.topOrder.length; i++) {
    //   console.log(this.topOrder[i] + " ");
    // }
  };

  getShortestPath = (source) => {
    let distance = [];
    for (let i = 0; i < this.V; i++) {
      distance[i] = Infinity;
    }
    distance[source] = 0;

    for (let i = 0; i < this.topOrder.length; i++) {
      let currentList = this.adjL[this.topOrder[i]];
      currentList.forEach((each) => {
        if (distance[each?.d] > distance[this.topOrder[i]] + each?.wt)
          distance[each?.d] = distance[this.topOrder[i]] + each?.wt;
      });
    }

    console.log(distance);
  };
}
// Example 1
graphInstance = new shortestPathInDAG(6);
graphInstance.addEdge(0, 1, 5);
graphInstance.addEdge(0, 2, 3);
graphInstance.addEdge(1, 3, 6);
graphInstance.addEdge(1, 2, 2);
graphInstance.addEdge(2, 4, 4);
graphInstance.addEdge(2, 5, 2);
graphInstance.addEdge(2, 3, 7);
graphInstance.addEdge(3, 4, -1);
graphInstance.addEdge(4, 5, -2);
graphInstance.getTopologicalSort();
graphInstance.getShortestPath(1);

// Example 2
graphInstance = new shortestPathInDAG(6);
graphInstance.addEdge(0, 1, 2);
graphInstance.addEdge(0, 4, 1);
graphInstance.addEdge(1, 2, 3);
graphInstance.addEdge(2, 3, 6);
graphInstance.addEdge(4, 5, 4);
graphInstance.addEdge(4, 2, 2);
graphInstance.addEdge(5, 3, 1);
graphInstance.getTopologicalSort();
graphInstance.getShortestPath(0);


Enter fullscreen mode Exit fullscreen mode

Top comments (0)