Getting Error: TypeError: Cannot read properties of undefined (reading 'push')

Viewed 23

I am getting error in this line(adj[it[0]].push(it[1]);) I am not able to understand why? this is code for finding Path in Directed Graph

Problem question: Given a directed graph having A nodes labeled from 1 to A containing M edges given by matrix B of size M x 2such that there is an edge directed from node

B[i][0] to node B[i][1].

Find whether a path exists from node 1 to node A.

Return 1 if the path exists else return 0.

let A = 5;
let B = [
  [1, 2],
  [4, 1],
  [2, 4],
  [3, 4],
  [5, 2],
  [1, 3],
];

function Queue() {
  var a = [],
    b = 0;
  this.getLength = function () {
    return a.length - b;
  };
  this.isEmpty = function () {
    return 0 == a.length;
  };
  this.enqueue = function (b) {
    a.push(b);
  };
  this.dequeue = function () {
    if (0 != a.length) {
      var c = a[b];
      2 * ++b >= a.length && ((a = a.slice(b)), (b = 0));
      return c;
    }
  };
  this.peek = function () {
    return 0 < a.length ? a[b] : void 0;
  };
}

let adj = new Array(A).fill([]);
console.log(adj);
let visited = new Array(A);
console.log(visited);
function ini() {
  for (let i = 0; i < A; i++) (adj[i] = []), (visited[i] = 0);
}
function isReachable(s, d) {
  if (s == d) return true;
  let q = new Queue();
  q.enqueue(s);
  visited[s] = 1;
  while (q.isEmpty() == false) {
    let s = q.dequeue();
    for (let i = 0; i < adj[s].length; i++) {
      let v = adj[s][i];
      if (v == d) return true;
      if (visited[v] == 0) {
        visited[v] = 1;
        q.enqueue(v);
      }
    }
  }
  return false;
}

function solve(A, B) {
  ini();
  for (let i = 0; i < B.length; i++) {
    let it = B[i];
   adj[it[0]].push(it[1]);
  }
  if (isReachable(1, A)) return 1;
  return 0;
}

console.log(solve(A, B));
0 Answers
Related