问题描述
我在使用 BFS 方法时遇到问题。
当我调用它时,如果我尝试在其他队列上使用 dequeue 方法,它会显示错误“无法读取未定义的‘长度’”,并且它会正确返回节点。
我还尝试在 for 循环中使用数字而不是 u.arr.length(问题出在哪里),它向我显示了与 u.arr[I].finalnode 相同的错误,表示“无法读取未定义的最终节点” .
我认为问题出在变量u的赋值上,但我不知道为什么。
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() {}
}
解决方法
您在 BFS 中执行 lista.enqueue(u.ar[i]);
,但 u.ar[i]
不是 Node
实例,而是在 { finalnode: n2,peso: p }
中创建的边缘对象 insertEdge
。
你会想要使用
for (i = 0; i < u.ar.length; i++) {
var finalnode = u.ar[i].finalnode;
finalnode.color = "grey";
finalnode.parent = u;
finalnode.d = u.d + 1;
lista.enqueue(finalnode);
// ^^^^^^^^^
}