我正在尝试用Javascript编写广度优先搜索算法,该算法还包括每个节点的重复次数。例如,在视频游戏制作菜单中,我要制作需要项目B x20,C x30和D x100的所需项目A。项目B,C和D依次需要其他项目乘以另一个任意数量。我想知道树的最底层需要多少个物品才能制作物品A。请尝试一下,我找不到解决方案。基本上,我正在“并行”执行物料的BFS和物料量的BFS。预期的输出是2D数组(2行,x列),第一行具有(唯一的)物料名称,第二行具有相关的物料数量。当前代码给我一个空白的结果。在搜索了StackOverflow,https://www.w3schools.com/jsref/jsref_obj_array.asp,https://www.geeksforgeeks.org/java-util-hashmap-in-java/和https://developer.mozilla.org/en-US/docs/Web/JavaScript之后,在8周的时间内,我已经写了10-20种版本。没运气,或者我对JS还是那么陌生,以至于我没有看到正确的答案。我从该函数调用的所有函数均正常运行(我分别对其进行了测试)。
function traversebreadth(key, keyamt, leaveschecked, repschecked, leavesqueue, repsqueue, roots, leaves, leafreps) { //initial parameters: string, number, [], [], string (same as key), number (same as keyamt), Array (column vector), 2D array (each row is a material list corresponding to the same row in "roots"), 2D array (each row is a material amount list corresponding to the same row in both "roots" and "leaves")
var keyleaves = getleaves(key, roots, leaves); //gets the leaves(/children) of the current node
var keyreps = getleafreps(key, roots, leafreps); //gets the children of the current node's repetitions (or "amounts")
keyreps = scalarmultiply(keyamt, keyreps); //multiplies the current repetitions by the number of repetitions of the parent node
leaveschecked += key; //push the key to the queue of checked nodes
repschecked += keyamt; //push the keyamt to the queue of checked node reps
if(!Array.isArray(leavesqueue)){ //ensure leavesqueue is an Object (Array), not a Number
var lq = [];
lq.push(leavesqueue);
leavesqueue = lq;
}
if(!Array.isArray(repsqueue)){ //ensure repsqueue is an Object (Array), not a Number
var rq = [];
rq.push(repsqueue);
repsqueue = rq;
}
if(isemptyarray(leavesqueue,"row")){ //if leavesqueue is empty, then there are no more leaves to check and this recursive function can return the result
return ArrayLib.transpose(leaveschecked).concat(ArrayLib.transpose(repschecked)); //return all of the unique nodes needed to craft item A, and the total amount of each node
}else{ //else, repeat this function
var newleavesqueue = queueleaves(keyleaves, leavesqueue); //queueleaves() appends keyleaves to leavesqueue and removes the first element of leavesqueue, then returns leavesqueue
var newrepsqueue = queueleafreps(keyreps,repsqueue); //queueleafreps() does the same thing as queueleaves() using keyreps and repsqueue
var newkey = ArrayLib.transpose(newleavesqueue).shift(); //gets the new node to use as current key
var newkeyamt = ArrayLib.transpose(newrepsqueue).shift(); //gets the reps of this new current key
traversebreadth(newkey, newkeyamt, leaveschecked, repschecked, newleavesqueue, newrepsqueue, roots, leaves, leafreps); //repeat this function with the new parameters
}