Last active
August 29, 2015 14:20
-
-
Save mattneary/355a5e8172de9c28f8ed to your computer and use it in GitHub Desktop.
Interview
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var marked = {}; | |
function markPoint(matrix, x, y) { | |
marked[x+","+y] = true; | |
} | |
function isPointMarked(matrix, x, y) { | |
return marked[x+","+y]; | |
} | |
function findNeighbors(matrix, x, y) { | |
return [-1, 0, 1].map(function (i) { | |
return [-1, 0, 1].map(function (j) { | |
return [i + x, j + y]; | |
}); | |
}).reduce(function (a, x) { | |
return a.concat(x); | |
}, []).filter(function (p) { | |
if (p[0] == x && p[1] == y) { | |
return false; | |
} | |
if (p[x] < 0 || p[x] >= matrix[0].length | |
|| p[y] < 0 || p[y] >= matrix.length) { | |
return false; | |
} | |
return true; | |
}); | |
} | |
function extendMarkedPoints(matrix) { | |
Object.keys(marked).map(function (p) { | |
return p.split(',').map(function (x) { | |
return parseInt(x); | |
}); | |
}).forEach(function (p) { | |
var neighbors = findNeighbors(matrix, p[0], p[1]); | |
var openMoves = neighbors.filter(function (p) { | |
return !isPointMarked(p[0], p[1]) && matrix[p[1]][p[0]] == 0; | |
}); | |
openMoves.forEach(function (p) { | |
markPoint(p[0], p[1]); | |
}); | |
}); | |
} | |
function shortestDistance(matrix, sX, sY, eX, eY) { | |
markPoint(matrix, sX, sY); | |
var steps = 0; | |
while (isPointMarked(eX, eY)) { | |
extendMarkedPoints(matrix); | |
steps += 1; | |
} | |
return steps; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment