Breadth First Search: Shortest Reach

  • + 1 comment

    Need help

    Language Typescript

    My solution is written in typescript... I will appreciate any help, to improve my code

    Test case passed (0,1,3,7)

    My solution succeeds to pass test cases 0, 1, 3, and 7... how ever when comparing manually the output obtained for test case 6 I have the same results, but some how my answer seems to be wrong

    My code is a follows

    function bfs(n: number, m: number, edges: number[][], s: number): number[] {
        // Creating a table of visited
        // each level represent a tree depth
        // placing the root node at depth 0
      let visited: number[][] = [[s]];
      let pos1: number[] = []; // stack of visited nodes
    
      for (let i = 0; i < visited.length; i++) {
        let nset = new Set<number>(); // set of nodes of a given level
        for (let j = 0; j < edges.length; j++) {
          let start = edges[j][0]; // node u
          let node = edges[j][1]; // node v
          
          // if node v is connected to a node at an upper level through u
          // then add node v
          
          // if instead node u is connected to a node at an upper level through v
          // then add node u
          if (visited[i].includes(start) && !pos1.includes(node)) {
            nset.add(node);
            pos1.push(node);
            edges.splice(j, 1);
            j--;
          } else if (visited[i].includes(node) && !pos1.includes(start)) {
            nset.add(start);
            pos1.push(start);
            edges.splice(j, 1);
            j--;
          }
        }
        
        // at the end of each level check, add the set of node to the visited stack if it has items
        if (nset.size > 0) {
          visited.push(Array.from<number>(nset));
        }
      }
      
      // creating an array of the visited nodes
      let res2 = new Set(visited.flat().sort((a, b) => a - b));
    
      // crating a response array filled with default values (-1)
      let res3: number[] = new Array(n).fill(-1);
    
      // inserting the visited elements in the respons array for checkup
      res2.forEach((e) => {
        res3[e - 1] = e;
      });
      
      // array to keep track of the checked positions
      let pos: number[] = [];
      
      res3.splice(res3.indexOf(s), 1);
    
      for (let i = 1; i < visited.length; i++) {
        for (let j = 0; j < visited[i].length; j++) {
          //if an element is found in the respons array 
          // and has not yet been checked, calculat its distance
          // according to its level in the visited table
          let index = res3.indexOf(visited[i][j]);
          if (!pos.includes(index) && index !== -1) {
            res3[index] = i * 6;
            
            //mark position as checked
            pos.push(index);
          }
        }
      }
    
      return res3;
    }