Created
May 3, 2016 18:34
-
-
Save bali182/228e6625e4826e7329f1c9cf0eb24558 to your computer and use it in GitHub Desktop.
Labyrinth solution
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
"use strict"; | |
function labyrinth(matrix) { | |
const rows = matrix.length, cols = matrix[0].length; // lets assume, that rows have the same length | |
const seen = new Array(rows).fill(1).map(_ => new Array(cols).fill(false)); // temp matrix of the same size as the input | |
function recursiveSolve(x, y) { | |
if (x === rows - 1 && y === cols - 1) return true; // we reached bottom right | |
if (matrix[x][y] !== 0 || seen[x][y]) return false; // no path :( | |
seen[x][y] = true; | |
return (x !== 0 && recursiveSolve(x - 1, y)) // left | |
|| (x !== rows - 1 && recursiveSolve(x + 1, y)) // right | |
|| (y != 0 && recursiveSolve(x, y - 1)) // up | |
|| (y != cols - 1 && recursiveSolve(x, y + 1)); // down | |
} | |
return recursiveSolve(0, 0); | |
} | |
function assert(value, message) { if (!value) throw new Error(message ? message : 'assertion error'); } | |
assert(labyrinth([[0, 0, 0, 0, 0], [1, 1, 1, 1, 0], [0, 0, 0, 0, 0], [0, 1, 1, 1, 1], [0, 0, 0, 0, 0]]) === true, 'should be true'); | |
assert(labyrinth([[0, 1, 1, 1, 1], [1, 1, 1, 1, 0], [0, 0, 0, 0, 0], [0, 1, 1, 1, 1], [0, 0, 0, 0, 0]]) === false, 'should be false'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment