최대 1 분 소요

part22. 리코쳇 로봇

js ver 1.0

function solution(board) {
    const map = {
        up: {x: 0, y: 1},
        down: {x: 0, y: -1},
        left: {x: -1, y: 0},
        right: {x: 1, y: 0},
    }

    const xSize = board[0].length;
    const ySize = board.length;

    const visited = Array.from({length: xSize}, () => Array(ySize).fill(0));

    const startPosition = board.reduce((result, row, idx) => {
        if (row.includes('R')) {
            result.x = row.indexOf('R');
            result.y = idx;
        }
        return result;
    }, {});

    function moveRobot(startPos) {
        visited[startPos.x][startPos.y] = 1;

        const queue = [startPos];

        while (queue.length) {
            const cur = queue.shift();

            for (const act in map) {
                let {x, y} = cur;

                while (true) {
                    x += map[act].x;
                    y += map[act].y;

                    if (!(x >= 0 && x < xSize)
                        || !(y >= 0 && y < ySize)
                        || board[y][x] == 'D') {

                        x -= map[act].x;
                        y -= map[act].y;
                        break;
                    }
                }

                if (!visited[x][y]) {
                    visited[x][y] = visited[cur.x][cur.y] + 1;
                    queue.push({x, y});
                }

                if (board[y][x] == 'G') {
                    return visited[x][y] - 1;
                }

            }
        }

        return -1;
    }

    return moveRobot(startPosition);
}


실행결과_js ver 1.0


업데이트: