I am creating a maze generation function, which requires uses recursive backtracking and obviously requires recursion. The function has to be run length * breath times, which sometimes exceeds the maximum recursion depth. The following is the code for the maze:
function maze(width, height){
var grid = [];
for (var y = 0; y < height; y++){
grid.push([]);
for (var x = 0; x < width; x++) grid[y].push(0);
}
function shuffle(){
var result = ["N", "S", "E", "W"];
for (var count = result.length; count > 0; count--){
rand = Math.floor(Math.random() * count);
[result[count - 1], result[rand]] = [result[rand], result[count - 1]];
}
return result;
}
function carve(curr_x, curr_y){
for (var dir of shuffle()){
var new_x = curr_x + {N: 0, S: 0, E: 1, W: -1}[dir], new_y = curr_y + {N: -1, S: 1, E: 0, W: 0}[dir];
if (new_y >= 0 && new_y <= height - 1 && new_x >= 0 && new_x <= width - 1 && grid[new_y][new_x] == 0){
grid[curr_y][curr_x] += {N: 1, S: 2, E: 4, W: 8}[dir];
grid[new_y][new_x] += {N: 2, S: 1, E: 8, W: 4}[dir];
carve(new_x, new_y);
}
}
}
carve(Math.floor(width / 3) + Math.floor(Math.random() * Math.floor(2 / 3 * width)), Math.floor(height / 3) + Math.floor(Math.random() * Math.floor(2 / 3 * height)));
return grid;
}
Given the definition of recursion, I believe that this function can be rewritten in requestAnimationFrame, so that the maximum recursion depth will not be exceeded. Is it possible? Are there any methods to convert recursion to something else? Thank you!