Manhattan distance

JavaScript

var map = [[0,0,0, 0,0,0, 0,0,0],
                [0,0,0, 0,0,1, 0,0,0],
                [1,0,0, 0,0,0, 0,0,0],
                [0,0,0, 0,0,0, 0,0,0],
                [0,0,0, 1,0,0, 0,0,0],
                [0,0,0, 0,0,0, 0,0,0],
                [0,0,0, 0,0,0, 0,0,0],
                [0,0,0, 0,0,0, 0,0,0],
                [0,0,0, 0,0,0, 0,0,1]];

var stations = [];

for (var y=0; y<map.length; y++)
{
    for (var x=0; x<map.length; x++)
    {
        if (map[y][x] > 0) {
            stations.push({ "x" : x, "y" : y });

        }
    }
}

$('body').append(stations);

for (var y=0; y<map.length; y++)
{
    for (var x=0; x<map.length; x++)
    {
        var dist = 99;
        for (var i=0; i<stations.length; i++)
        {
            var newdistance = mdistance(x,y,stations[i].x,stations[i].y)
            if (newdistance < dist) {
                dist = newdistance;
            }
        }
        $('body').append(dist);
    }
    $('body').append('<br>');
}

function mdistance(x1,y1,x2,y2)
{
    return Math.abs(x2-x1) + Math.abs(y2-y1);
}