[Lv.1] 공원 산책

01수정·2023년 11월 15일
0

문제





풀이

1) 1차 풀이 : 틀림
중간 도착지점 뿐 만 아니라 중간 도착지점을 가는 '길목' 에도 장애물이 있으면 안되기 때문.. !

function solution(park, routes) {
    let map = park.reduce((acc, val, idx) => acc[idx] = [...val], []);
    const width = park[0].length;
    const height = park.length;

    let prev_position = [0, 0];
    let next_position = [0, 0];

    for (const route of routes) {
        const [direction, move] = route.split(' ');
    
        if (direction === 'N') {
            next_position[0] -= move*1;
        } else if (direction === 'E') {
            next_position[1] += move*1;
        } else if (direction === 'S') {
            next_position[0] += move*1;
        } else if (direction === 'W') {
            next_position[1] -= move*1;
        }

        if (map[next_position] !== 'X'
           && next_position[0] <= width
           && next_position[1] <= height) {
            map[prev_position] = 'O';
            map[next_position] = 'S';
            prev_position = next_position;
        }

    }

    return prev_position;    
}

2) 2차 풀이

function solution(park, routes) {
    const width = park.length;
    const height = park[0].length;
    const directions = {
        E: [0, 1], 
        W: [0, -1], 
        S: [1, 0], 
        N: [-1, 0]
    }

    // 시작지점 구하기
    let position;
    for (let i=0; i<width; i++) {
        for (let j=0; j<height; j++) {
            if (park[i][j] === 'S') {
                position = [i, j];
                break;
            }
        }
    }

    // 이동하기 
    for (const route of routes) {
        const [dir, dist] = route.split(' ');
        let distance = dist * 1
        let [x, y] = position;
        
        let flag = true;
        for (let i=0; i<distance; i++) {
            x += directions[dir][0];
            y += directions[dir][1];

            if (
                x < 0 
                || x >= width
                || y < 0
                || y >= height
                || park[x][y] === 'X'
            ) {
                flag = false;
                break;
            }
        }

        if (flag) {
            position = [x, y];
        }
    }

   return position;
}

다른 풀이

function solution(park, routes) {
        const dirs = { E: [0, 1], W: [0, -1], S: [1, 0], N: [-1, 0] };
        let [x, y] = [0, 0];
        for (let i = 0; i < park.length; i++) {
          if (park[i].includes('S')) {
            [x, y] = [i, park[i].indexOf('S')];
            break;
          }
        }

        routes.forEach((route) => {
          const [r, n] = route.split(' ');
          let [nx, ny] = [x, y];
          let cnt = 0;
          while (cnt < n) {
            [nx, ny] = [nx + dirs[r][0], ny + dirs[r][1]];
            if (!park[nx] || !park[nx][ny] || park[nx][ny] === 'X') break;
            cnt++;
          }
          if (cnt == n) [x, y] = [nx, ny];
        });
        return [x, y];
      }
profile
새싹 FE 개발자

0개의 댓글