Maze minimum path

by Alex Myronov

Babel + JSX

function isPathAllowed(maze, visited, dest) {
  if (dest.x >= 0 && dest.y >= 0 &&
    dest.x < maze.length &&
     dest.y < maze[0].length &&
     maze[dest.x][dest.y] === 1 &&
     !visited[dest.x][dest.y]) {
    return true
  }
  return false
}

var minDist = 1000

function findPath(maze, visited, source, dest, dist) {

  if (source.x === dest.x && source.y === dest.y) {
    minDist = Math.min(minDist, dist)
  } else {
  visited[source.x][source.y] = true

  if (isPathAllowed(maze, visited, { x: source.x + 1, y: source.y })) {
    findPath(maze, visited, { x: source.x + 1, y: source.y }, dest, dist + 1)
  }
  
  if (isPathAllowed(maze, visited, { x: source.x, y: source.y + 1 })) {
    findPath(maze, visited, { x: source.x, y: source.y + 1 }, dest, dist + 1)
  }
  
  if (isPathAllowed(maze, visited, { x: source.x - 1, y: source.y })) {
    findPath(maze, visited, { x: source.x - 1, y: source.y }, dest, dist + 1)
  }
  
  if (isPathAllowed(maze, visited, { x: source.x, y: source.y -1 })) {
    findPath(maze, visited, { x: source.x, y: source.y - 1}, dest, dist + 1)
  }
  
  visited[source.x][source.y] = false
  }

}

var vMaze = [
  [1, 1, 1, 1, 1, 0, 0, 1, 1, 1],
  [0, 1, 1, 1, 1, 1, 0, 1, 0, 1],
  [0, 0, 1, 0, 1, 1, 1, 0, 0, 1],
  [1, 0, 1, 1, 1, 0, 1, 1, 0, 1],
  [0, 0, 0, 1, 0, 0, 0, 1, 0, 1],
  [1, 0, 1, 1, 1, 0, 0, 1, 1, 0],
  [0, 0, 0, 0, 1, 0, 0, 1, 0, 1],
  [0, 1, 1, 1, 1, 1, 1, 1, 0, 0],
  [1, 1, 1, 1, 1, 0, 0, 1, 1, 1],
  [0, 0, 1, 0, 0, 1, 1, 0, 0, 1],
]

var visited = vMaze.map((row) => row.map(() => 0))

findPath(vMaze, visited, { x: 0, y: 0 }, { x: 7, y: 5 }, 0)

console.log(minDist)