Skip to content

Instantly share code, notes, and snippets.

@RP-3
Created February 16, 2020 22:45
Show Gist options
  • Save RP-3/fa3de4dffb76775c6aff9ce87a35daea to your computer and use it in GitHub Desktop.
Save RP-3/fa3de4dffb76775c6aff9ce87a35daea to your computer and use it in GitHub Desktop.
/**
* @param {number[][]} grid
* @return {number}
*/
var uniquePathsIII = function(grid) {
const visited = new Array(grid.length).fill(0).map(() => new Array(grid[0].length).fill(0));
let visitedCount = 0;
const squaresToVisit = countNonObstacleSquares(grid);
const traverse = (i, j) => {
if(grid[i][j] === 2){ // we found the end
if(visitedCount === squaresToVisit + 1) return 1;
return 0;
}
const traversalResults = [
[i, j+1], // move down
[i, j-1], // move up
[i+1, j], // move right
[i-1, j] // move left
].filter(([y, x]) => {
if(y < 0 || y >= grid.length) return false; // y/i out of bounds
if(x < 0 || x >= grid[0].length) return false; // x/j out of bounds
if(grid[y][x] === 1) return false // back at start
if(grid[y][x] === -1) return false // cannot walk over
if(visited[y][x] === 1) return false // already visited
return true;
})
.map(([y, x]) => {
visited[y][x] = 1; // mark as visited
visitedCount++;
const result = traverse(y, x);
visited[y][x] = 0; // backtrack
visitedCount--;
return result;
})
.reduce((a, b) => a + b, 0);
return traversalResults;
};
const [i, j] = findStart(grid);
return traverse(i, j);
};
function countNonObstacleSquares(grid) {
let count = 0;
for(let i=0; i<grid.length; i++) {
for(let j=0; j<grid[i].length; j++){
if(grid[i][j] === 0) count++;
}
}
return count;
}
function findStart(grid) {
for(let i=0; i<grid.length; i++) {
for(let j=0; j<grid[i].length; j++){
if(grid[i][j] === 1) return [i, j];
}
}
throw new Error('Grid does not contain a start (1) square');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment