Code:
var findPath = function (maze) {
const visited = {},
path = []
const end = [maze.length - 1, maze[0].length - 1]
function nextPath(path, cur) {
if (!Array.isArray(maze[cur[0]]) || maze[cur[0]][cur[1]] !== 1) {
return false
}
visited[cur[0]] = visited[cur[0]] || {}
if (visited[cur[0]][cur[1]]) {
return false
} else {
path.push(cur)
visited[cur[0]][cur[1]] = true
if (cur[0] === end[0] && cur[1] === end[1]) {
return true
}
let result =
nextPath(path, [cur[0] - 1, cur[1]]) ||
nextPath(path, [cur[0] + 1, cur[1]]) ||
nextPath(path, [cur[0], cur[1] - 1]) ||
nextPath(path, [cur[0], cur[1] + 1])
result || path.splice(-1, 1)
return result
}
}
nextPath(path, [0, 0])
if (path.length > 0) {
let copy = JSON.parse(JSON.stringify(maze))
path.forEach(ind => (copy[ind[0]][ind[1]] = 2))
const log = copy
.map(it => it.map(v => (v === 2 ? '%c2%c' : `${v}`)).join(' '))
.map((a, i) => (i === 0 ? '\n' + a : a))
.join('\n')
.replace(/%c(\s)%c/g, '$1')
const style = Array(log.match(/%c/g).length)
.fill(0)
.map((_, i) => (i % 2 === 0 ? 'color:red' : 'color:black'))
console.log(log, ...style)
} else {
console.log('%cInarrivable!', 'color:red')
}
return path
}
Input:
[
[1, 0, 1],
[1, 1, 0],
[0, 1, 1]
]
Output:
[
[0,0],
[1,0],
[1,1],
[2,1],
[2,2]
]
Stdout:
2 0 1
2 2 0
0 2 2