# javascript – 将递归算法转换为迭代算法的困难

>创建一个包含单元状态表示的堆栈.
>每个表示保存特定单元格的坐标,以及访问相邻单元格的方向列表.
>当堆栈不为空时,迭代堆栈顶部的方向,测试相邻的单元格.
>如果找到有效单元格,则将其放在堆栈顶部并继续该单元格.

var dirs = [ 'N', 'W', 'E', 'S' ];
var XD = { 'N': 0, 'S':0, 'E':1, 'W':-1 };
var YD = { 'N':-1, 'S':1, 'E':0, 'W': 0 };

function genMaze(){

var dirtemp = dirs.slice().slice();    //copies 'dirs' so its not overwritten or altered
var path = [];                         // stores path traveled.

var stack = [[0,0, shuffle(dirtemp)]]; //Stack of instances. Each subarray in 'stacks' represents a cell
//and its current state. That is, its coordinates, and which adjacent cells have been
//checked. Each time it checks an adjacent cell a direction value is popped from
//from the list

while ( stack.length > 0 ) {

var current = stack[stack.length-1]; // With each iteration focus is to be placed on the newest cell.

var x = current[0], y = current[1], d = current[2];
var sLen = stack.length;             // For testing whether there is a newer cell in the stack than the current.
path.push([x,y]);                    // Store current coordinates in the path

while ( d.length > 0 ) {
if( stack.length != sLen ){ break;}// If there is a newer cell in stack, break and then continue with that cell

else {
var cd = d.pop();
var nx = x + XD[ cd ];
var ny = y + YD[ cd ];

if ( nx >= 0 && ny >= 0  && nx < w && ny < h && !cells[nx][ny] ){

dtemp = dirs.slice().slice();
cells[nx][ny] = 1;
stack.push( [ nx, ny, shuffle(dtemp) ] ); //add new cell to the stack with new list of directions.
// from here the code should break from the loop and start again with this latest addition being considered.

}
}

}

if (current[2].length === 0){stack.pop(); } //if all available directions have been tested, remove from stack

}
return path;
}

function genMaze(cx,cy) {

var dirtemp = dirs;    //copies 'dirs' so its not overwritten
var path = [];                         // stores path traveled.
var stack = [[cx, cy, shuffle(dirtemp), 0]];  // we also need to store `for` indexer

while (stack.length > 0) {

var current = stack[stack.length - 1]; // With each iteration focus is to be placed on the newest cell.

var x = current[0], y = current[1], d = current[2], i = current[3];
if (i > d.length) {
stack.pop();
continue;
}
stack[stack.length - 1][3] = i + 1; // for next iteration

path.push([x, y]);    // Store current coordinates in the path
cells[x][y] = 1;

var cd = d[i];
var nx = x + XD[cd];
var ny = y + YD[cd];

if (nx >= 0 && ny >= 0 && nx < w && ny < h && !cells[nx][ny]) {

dtemp = dirs;
stack.push([nx, ny, shuffle(dtemp), 0]);
}
}
return path;
}

每一个你不满意的现在，都有一个你没有努力的曾经。
一个历史类的公众号，欢迎关注