Skip to content

Instantly share code, notes, and snippets.

@ferndot
Last active August 3, 2020 02:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ferndot/2326ba53597e2b4236aed30cf567e790 to your computer and use it in GitHub Desktop.
Save ferndot/2326ba53597e2b4236aed30cf567e790 to your computer and use it in GitHub Desktop.
function allMaze(x, y, maze) {
let validPaths = []
if (y < 0 || x < 0 || y > maze.length - 1 || x > maze[y].length - 1) {
return false
} else if (maze[y][x] === "e") {
return ['']
} else if (maze[y][x] == "*") {
return false
}
let newMaze = [...maze]
newMaze[y] = [...maze[y]]
newMaze[y][x] = "H"
for (const line of newMaze) {
console.log(line.join(' '))
}
console.log("\n\n")
newMaze[y][x] = "*"
downPaths = allMaze(x, y + 1, newMaze)
if (downPaths !== false) {
for (const path of downPaths) {
validPaths.push("D" + path)
}
}
rightPaths = allMaze(x + 1, y, newMaze)
if (rightPaths !== false) {
for (const path of rightPaths) {
validPaths.push("R" + path)
}
}
upPaths = allMaze(x, y - 1, newMaze)
if (upPaths !== false) {
for (const path of upPaths) {
validPaths.push("U" + path)
}
}
leftPaths = allMaze(x - 1, y, newMaze)
if (leftPaths !== false) {
for (const path of leftPaths) {
validPaths.push("L" + path)
}
}
if (validPaths.length === 0) {
return false
}
return validPaths
}
maze = [
[" ", " ", " ", "*", " ", " ", " "],
["*", "*", " ", "*", " ", "*", " "],
[" ", " ", " ", " ", " ", " ", " "],
[" ", "*", "*", "*", "*", "*", " "],
[" ", " ", " ", " ", " ", " ", "e"],
]
paths = allMaze(0, 0, maze)
console.log(paths)
def allMaze(x, y, maze):
validPaths = []
if y < 0 or x < 0 or y > len(maze) - 1 or x > len(maze[y]) - 1:
return False
elif maze[y][x] == "e":
return [""]
elif maze[y][x] == "*":
return False
newMaze = list(maze)
newMaze[y] = list(newMaze[y])
newMaze[y][x] = "H"
for line in newMaze:
print(" ".join(line))
print("\n\n")
newMaze[y][x] = "*"
downPaths = allMaze(x, y + 1, newMaze)
if downPaths is not False:
for path in downPaths:
validPaths.append("D" + path)
rightPaths = allMaze(x + 1, y, newMaze)
if rightPaths is not False:
for path in rightPaths:
validPaths.append("R" + path)
upPaths = allMaze(x, y - 1, newMaze)
if upPaths is not False:
for path in upPaths:
validPaths.append("U" + path)
leftPaths = allMaze(x - 1, y, newMaze)
if leftPaths is not False:
for path in leftPaths:
validPaths.append("L" + path)
if not validPaths:
return False
return validPaths
maze = [
[" ", " ", " ", "*", " ", " ", " "],
["*", "*", " ", "*", " ", "*", " "],
[" ", " ", " ", " ", " ", " ", " "],
[" ", "*", "*", "*", "*", "*", " "],
[" ", " ", " ", " ", " ", " ", "e"],
]
paths = allMaze(0, 0, maze)
print(paths)
assert "RRDDLLDDRRRRRR" in paths
assert "RRDDRRRRDD" in paths
assert "RRDDRRUURRDDDD" in paths
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment