Labirynth generator

Transcription from Python example in http://en.m.wikipedia.org/wiki/Maze_generation_algorithm

HTML

<canvas id="canvas" width="300" height="250">
</canvas>

JavaScript

var ncols = 25;
var nrows = 21;
var scale = 10;

// creates a two-dimensional array 
function maze_init(h, w) {
    var Z = [];
    for (var i = 0; i < h; ++i) {
        Z[i] = new Array(w);
        for (var j = 0; j < w; ++j) {
            var v;
            // external wall
            if (i === 0 || j === 0 || i === (h - 1) || j === (w - 1)) v = 1;
            else v = 0;
            // door to enter
            if (i === 0 && j === 1 || i === (h - 1) && j === (w - 2))
                v = 0;
            // door to exit
            Z[i][j] = v;
        }
    }
    return Z;
}
function print_results() {
    //print_message(t1);    print_message(t2);
    print_message("done, time (s): " + String((t2 - t1)/1000) + ". Click to go to next level.");
}

function random_range(r) {
    return Math.floor(Math.random() * r);
}

function maze(width, height, complexity, density) {
    if (!width) width = 81;
    if (!height) height = 51;
    if (!complexity) complexity = 0.75;
    if (!density) density = 0.75;
    // Only odd shapes
    height = Math.floor(height / 2) * 2 + 1;
    width = Math.floor(width / 2) * 2 + 1;
    // Adjust complexity and density relative to maze size
    complexity = Math.round(complexity * (5 * (height + width)));
    density = Math.round(density * (Math.floor(height / 2) * Math.floor(width / 2)));
    // Build actual maze
    Z = maze_init(height, width);
    //density = 1;
    // Make isles
    for (i = 0; i < density; ++i) {
        x = random_range(Math.ceil(width / 2)) * 2;
        y = random_range(Math.ceil(height / 2)) * 2;
        Z[y][x] = 1;
//complexity = 1;
        for (j = 0; j < complexity; ++j) {
            neighbours = [];
            if (x > 1) neighbours.push({
                y: y,
                x: x - 2
            });
            if (x < width - 2) neighbours.push({
                y: y,
                x: x + 2
            });
            if (y > 1) neighbours.push({
                y: y - 2,
                x: x
        ...