【发布时间】:2012-05-26 12:39:22
【问题描述】:
我将使用这个用 C 编写的简单的迷宫解算程序来举例说明我在 javascript 中需要什么:
int is_free_place(int x,int y) {
char ch[2];
if(x<1||x>80||y<1||y>20)
return 0;
gettext(x,y,x,y,ch);
return ch[0]==32; // X or space
}
int solve(int x, int y, int x_end,int y_end) {
int ans=0;
if(kbhit()) efn();
gotoxy(x,y);
putchar('.');
delay(DELAY_TIME);
if(x==x_end&&y==y_end)
return 1;
if(is_free_place(x-1,y))
ans=solve(x-1,y,x_end,y_end); //// <<<<< recursion starts here
if(ans==0&&is_free_place(x+1,y)) //// can't continue to here if using setTimeout
ans=solve(x+1,y,x_end,y_end); //// because ans is not set
if(ans==0&&is_free_place(x,y-1))
ans=solve(x,y-1,x_end,y_end);
if(ans==0&&is_free_place(x,y+1))
ans=solve(x,y+1,x_end,y_end);
if(ans==0){
gotoxy(x,y);
putchar(' ');
delay(DELAY_TIME);
}
return ans;
}
void main(){
clrscr();
efn(); // reads maze from file, shows menu, calls solve()
}
我正在尝试在 javascript 中进行类似的递归,但浏览器会冻结,直到代码完成,我需要的是一个缓慢的进度动画,可以选择暂停和更改内容。所以我尝试使用setTimeout,但我无法弄清楚函数何时“返回”并且代码从递归调用继续的算法...... (setTimeout 立即继续,不等待函数返回)
[更新] 有没有办法使用yield而不是使用堆栈来做到这一点?
【问题讨论】:
-
我们不会为你编写所有的 JS。向我们展示你所拥有的(希望比 C 版本更具可读性)。
-
我不需要JS中的所有C代码;)我只需要返回部分的想法(我知道setTimeout返回id,我说的是setTimeout函数的返回电话)所以我可以做一个不同的,更大的项目......
标签: javascript c++ recursion return settimeout