我正在尝试编写程序来计算 p5.js 中最大的颜色连接 block 。问题是,当我递归调用它给出的框邻居时 - “最大调用堆栈超出”,我知道错误的含义,但我不知道为什么会发生。这是我的代码:
class Box {
constructor(id, x, y, w, h, col, colId) {
this.id = id;
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.col = col;
this.colId = colId;
}
render() {
fill(this.col);
stroke(1);
rect(this.x * this.w, this.y * this.w, this.w, this.h);
}
getNeighbour(visited, x, y) {
if(x - 1 < 0 || x + 1 >= rows || y - 1 < 0 || y + 1 >= cols) {
return -1;
}
else {
this.col = color(10,10,10);
arr[x-1][y].getNeighbour(visited,x-1,y);
arr[x+1][y].getNeighbour(visited,x+1,y);
arr[x][y-1].getNeighbour(visited,x,y-1);
arr[x][y+1].getNeighbour(visited,x,y+1);
}
if(!this.contains(this.id)) {
visited.push(this.id);
}
}
contains() {
for(let i = 0; i < visited.length; i++) {
if(this.id == visited[i]) return true;
}
return false;
}
}
请告诉我问题出在哪里。我当时也试过做检查。首先是左边的邻居,效果很好。但是,当我也添加正确的时,会出现此错误。我想我已经满足了适当的默认情况,但实际情况可能有所不同。
最佳答案
代替:
else {
this.col = color(10,10,10);
arr[x-1][y].getNeighbour(visited,x-1,y);
arr[x+1][y].getNeighbour(visited,x+1,y);
arr[x][y-1].getNeighbour(visited,x,y-1);
arr[x][y+1].getNeighbour(visited,x,y+1);
}
if(!this.contains(this.id)) {
visited.push(this.id);
}
尝试:
else if(!this.contains(this.id)) {
visited.push(this.id);
this.col = color(10,10,10);
arr[x-1][y].getNeighbour(visited,x-1,y);
arr[x+1][y].getNeighbour(visited,x+1,y);
arr[x][y-1].getNeighbour(visited,x,y-1);
arr[x][y+1].getNeighbour(visited,x,y+1);
}
进一步:我不确定 this.contains
是否正确,也许可以尝试:visited.contains...
?
关于javascript - JS最大调用栈超过P5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59812726/