Javascript JS最大调用堆栈超过P5

Javascript JS最大调用堆栈超过P5,javascript,class,object,recursion,p5.js,Javascript,Class,Object,Recursion,P5.js,我试图制作一个程序来计算p5.js中最大的颜色连接块。问题是,当我递归调用与它相邻的框时,它给出了“最大调用堆栈超过”,我知道错误的含义,但我不知道为什么会发生。这是我的密码: 类框{ 构造函数(id、x、y、w、h、col、colId){ this.id=id; 这个.x=x; 这个。y=y; 这个.w=w; 这个,h=h; this.col=col; this.colId=colId; } render(){ 填充(本栏); 中风(1); rect(this.x*this.w,this.y

我试图制作一个程序来计算p5.js中最大的颜色连接块。问题是,当我递归调用与它相邻的框时,它给出了“最大调用堆栈超过”,我知道错误的含义,但我不知道为什么会发生。这是我的密码:

类框{
构造函数(id、x、y、w、h、col、colId){
this.id=id;
这个.x=x;
这个。y=y;
这个.w=w;
这个,h=h;
this.col=col;
this.colId=colId;
}
render(){
填充(本栏);
中风(1);
rect(this.x*this.w,this.y*this.w,this.w,this.h);
}
获取邻居(已访问,x,y){
如果(x-1<0 | | x+1>=行| | y-1<0 | | y+1>=列){
返回-1;
}
否则{
this.col=颜色(10,10,10);
arr[x-1][y].getNeighbor(已访问,x-1,y);
arr[x+1][y].getNeighbor(已访问,x+1,y);
arr[x][y-1].getNeighbor(已访问,x,y-1);
arr[x][y+1].getNeighbor(已访问,x,y+1);
}
如果(!this.contains(this.id)){
visitored.push(this.id);
}
}
包含(){
for(设i=0;i<0.length;i++){
if(this.id==visted[i])返回true;
}
返回false;
}

}
当您从一个框开始时,它会在框的左侧、右侧、上方和下方递归。 这四个盒子也是如此。 但是如果你在上面的框中,它调用下面的框,你就回到了开始的地方。这会来回移动,直到堆栈用完

根据您尝试执行的操作,一个简单的解决方案是拉动“包含”检查,如果之前访问过该框,则中止:

getNeighbor(已访问,x,y){
if(isOutsideBounds(x,y)| visitored.indexOf(this.id)>-1){
返回-1;
}
this.col=颜色(10,10,10);
visited.push(this.id)
arr[x-1][y].getNeighbor(已访问,x-1,y);
arr[x+1][y].getNeighbor(已访问,x+1,y);
arr[x][y-1].getNeighbor(已访问,x,y-1);
arr[x][y+1].getNeighbor(已访问,x,y+1);
}  
另外,您的
contains()
函数似乎访问了已访问的
数组,该数组不在函数的作用域中。

而不是:

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); 
}
尝试:


进一步:我不确定
this.contains
是否正确,也许可以尝试:
visted.contains…

这是一种抽象方法。你可以拿一个岛上柜台,清点每个岛上的物品

功能检查(数组){
功能测试(数组、i、j、值){
if(数组[i]&数组[i][j]=-1){
计数[值]=(计数[值]| | 0)+1;
数组[i][j]=值;
测试(数组,i-1,j,值);
测试(数组,i+1,j,值);
测试(数组,i,j-1,值);
测试(数组,i,j+1,值);
返回true;
}
}
var值=1,
计数={};
array.forEach(a=>a.forEach((b,i,bb)=>bb[i]=-b));
array.forEach((a,i,aa)=>a.forEach((b,j)=>test(aa,i,j,value)&&value++);
map(a=>console.log(…a));
返回计数;
}
log(检查([[1,0,1],[1,0,0],[1,1,1]]);
log(检查([[1,0,1],[0,1,0],[1,0,1]]);
日志(检查([[1,0,0,1,1],[1,1,1,0,0],[0,0,1,0,1],[0,0,1,0,1],[1,1,1,0,1])

。作为控制台包装{max height:100%!important;top:0;}
在堆栈旁边,如果不需要检查值,为什么要提前检查所有索引(
x
y
),因为方向是可能的。我想你应该在调用
getneighbor
之前进行检查。我稍后会检查值,但为了方便起见,我删除了它。如果某个框被访问了,检查在哪里?
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);
}