Floyd : City of Blinding Lights

  • + 0 comments

    Js

    function shortestPath(roadNodes, edges, queries) {
        let matrix = Array(roadNodes);
        for (let i = 0; i < roadNodes; i++) {
            matrix[i] = Array(roadNodes)
            for (let j = 0; j < roadNodes; j++) {
                if (j === i) {
                    matrix[i][j] = 0;
                    continue;
                }
                matrix[i][j] = Number.MAX_SAFE_INTEGER;
            }
        }
        
        for (const edge of edges) {
            matrix[edge[0]-1][edge[1]-1] = edge[2];
        }
        
        for (let i = 0; i < roadNodes; i++) {
            for (let j = 0; j < roadNodes; j++) {
                for (let k = 0; k < roadNodes; k++) {
                    let op = matrix[j][i] + matrix[i][k];
                    matrix[j][k] = Math.min(matrix[j][k], op)
                }
            }
        }
        
        for (const query of queries) {
            console.log(matrix[query[0]-1][query[1]-1] !== Number.MAX_SAFE_INTEGER ? matrix[query[0]-1][query[1]-1] : -1)
        }
    }