I'm having problems with the BFS method.
When I call it shows me the error "cannot read 'length' of undefined" if I try to use the dequeue method on other queues it works, and it returns the node correctly.
I also tried to use a number instead of u.arr.length in the for loop(where are the problems) and it shows me the same error with u.arr[I].finalnode that says "cannot read final node of undefined".
I think the problem is in the assignment of variable u, but I don't why.
class Node {
//declaration of graph's nodes
constructor(nome) {
this.nome = nome;
this.ar = [];
}
}
class Item {
//declaration of list's elements
constructor(data, next) {
this.data = data;
this.next = null;
}
}
class Queue {
//declaration of list class
constructor(head) {
this.head = null;
this.tail = null;
this.size = 0;
}
enqueue(s) {
var i = new Item(s);
if (this.size == 0) {
this.head = i;
this.tail = i;
this.size++;
} else {
if (this.size == 1) {
this.tail = i;
this.head.next = this.tail;
this.size++;
}
if (this.size > 1) {
this.tail.next = i;
this.tail = this.tail.next;
this.size++;
}
}
}
dequeue() {
var s = this.head;
this.head = this.head.next;
this.size--;
return s.data;
}
}
class Graph {
//declaration of graph class
constructor() {
this.arr = [];
}
insertnode(n) {
this.arr.push(n);
}
insertedge(n1, n2, p) {
n1.ar.push({ finalnode: n2, peso: p });
}
BFS(s) {
var i;
var u;
var lista = new Queue();
for (i = 0; i < this.arr.length; i++) {
this.arr[i].color = "white";
this.arr[i].d = Infinity;
this.arr[i].parent = null;
}
s.color = "grey";
s.d = 0;
lista.enqueue(s);
console.log(lista);
while (lista.head != null) {
u = lista.dequeue();
for (i = 0; i < u.ar.length; i++) {
//here is the problem
u.ar[i].finalnode.color = "grey";
u.ar[i].finalnode.parent = u;
u.ar[i].finalnode.d = u.d + 1;
lista.enqueue(u.ar[i]);
}
u.color = "black";
}
}
DFS() {}
}