DEV Community

loading...

Discussion on: Daily Challenge #288 - Maze Runner

Collapse
_bkeren profile image
'' • Edited

ES6

const find = (maze, N, num) => {
    for (let i = 0; i < N; i++) {
        let index = maze[i].indexOf(num)
        if (index > -1) return [i, index]
    }
    return -1
}


const reach = (maze, direction) => {
    if (!maze || !Array.isArray(maze) || maze[0].length !== maze.length) throw new Error("invalid argument")
    const N = maze[0].length
    let start = find(maze, N, 2)
    if (start < 0) throw new Error("start point not found")
    let finish = find(maze, N, 3)
    if (finish < 0) throw new Error("finish point not found")
    for (let i = 0; i < direction.length; i++) {
        switch (direction[i]) {
            case "E":
                start = [start[0], start[1] + 1];
                break;
            case "W":
                start = [start[0], start[1] - 1]
                break;
            case "N":
                start = [start[0] - 1, start[1]]
                break;
            case "S":
                start = [start[0] + 1, start[1]]
                break;
            default:
                throw new Error("unidentified direction")
        }
        if (start[0] < 0 || start[0] >= N || start[1] < 0 || start[1] >= N || maze[start[0]][start[1]] === 1) {
            return "Dead"
        }

    }
    if (start[0] === finish[0] && start[1] === finish[1]) return "Finish"

    return "Lost"
}