Skip to content

Instantly share code, notes, and snippets.

@bali182
Created May 3, 2016 18:34
Show Gist options
  • Save bali182/228e6625e4826e7329f1c9cf0eb24558 to your computer and use it in GitHub Desktop.
Save bali182/228e6625e4826e7329f1c9cf0eb24558 to your computer and use it in GitHub Desktop.
Labyrinth solution
"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