Created
December 11, 2019 21:59
-
-
Save indie-rok/fca0cbcc701d5ea4318a4349933027d9 to your computer and use it in GitHub Desktop.
This file contains 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
module.exports = function solve(maze, miner, exit) { | |
let directionsArray = ["up", "right", "down", "left"]; | |
const movements = { | |
left: { x: -1, y: 0 }, | |
right: { x: 1, y: 0 }, | |
up: { x: 0, y: -1 }, | |
down: { x: 0, y: 1 } | |
}; | |
const xNum = maze.length; | |
const yNum = maze[0].length; | |
const xTarget = exit.x; | |
const yTarget = exit.y; | |
const path = []; | |
const visited = []; | |
for (let x = 0; x < xNum; ++x) { | |
visited.push([]); | |
for (let y = 0; y < yNum; ++y) { | |
visited[x].push(false); | |
} | |
} | |
function dfs(x, y) { | |
if (x == xTarget && y == yTarget) { | |
return true; | |
} | |
for (let i = 0; i < directionsArray.length; ++i) { | |
let delta = movements[directionsArray[i]]; | |
x += delta.x; | |
y += delta.y; | |
if ( | |
x < xNum && | |
y >= 0 && | |
x >= 0 && | |
y < yNum && | |
!visited[x][y] && | |
maze[x][y] | |
) { | |
path.push(directionsArray[i]); | |
visited[x][y] = true; | |
if (dfs(x, y)) { | |
return true; | |
} | |
visited[x][y] = false; | |
path.pop(); | |
} | |
x -= delta.x; | |
y -= delta.y; | |
} | |
return false; | |
} | |
visited[miner.x][miner.y] = true; | |
dfs(miner.x, miner.y); | |
return path; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment