Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function solution(A, B, C, D) {
- if(D.length === 0) return -1;
- if(D[0] >= 0) return 0; // we don't need to move
- if(A.length === 0 || B.length === 0 || C.length === 0) return -1;
- let isAllClosed = true;
- for(let i = 0; i < D.length; i++){
- if(D[i] !== -1) {
- isAllClosed = false;
- }
- }
- if(isAllClosed) return -1;
- // build graph
- let graph = {}; // would adjacency matrix be better?
- for(let i = 0; i < A.length; i++){
- let source = A[i];
- let target = B[i];
- let cost = C[i];
- // one direction
- if(graph[source] === undefined){ // /!\ undirect graph, must add in both directions
- // one direction
- graph[source] = new Map();
- graph[source].set(target, cost);
- } else {
- let present = graph[source];
- if(present.has(target)){
- // did we find a shorter path for something already in there?
- let currentCost = present.get(target);
- if(currentCost > cost){
- graph[source].set(target, cost);
- }
- } else {
- // path not yet present
- present.set(target, cost);
- }
- }
- // other direction
- if(graph[target] === undefined){ // /!\ undirect graph, must add in both directions
- // one direction
- graph[target] = new Map();
- graph[target].set(source, cost);
- } else {
- let present = graph[target];
- if(present.has(source)){
- // did we find a shorter path for something already in there?
- let currentCost = present.get(source);
- if(currentCost > cost){
- graph[target].set(source, cost);
- }
- } else {
- // path not yet present
- present.set(source, cost);
- }
- }
- }
- // at this point, we have built the graph
- // we start from square 0
- let visited = new Array(A.length);
- visited.fill(false);
- let start = graph[0];
- if(start === undefined || start.size < 1) return -1; // cannot move around
- visited[0] = true;
- let queue = [];
- for(let [key, value] of start){
- queue.push({target: key, cost:value});
- }
- while(queue.length !== 0){
- let current = queue.shift();
- visited[current.target] = true;
- if(D[current.target] >= current.cost){
- // open shop
- return current.cost;
- }
- // prepare other children
- let next = graph[current.target];
- for(let [key, value] of next){
- if(!visited[key]){
- queue.push({target: key, cost:(value+current.cost)});
- }
- }
- }
- return -1;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement