백준 SILVER 2(이동하기)

image

  • 사용 언어 : javascript

  • 해결 날짜 : 2023-02-05

  • 해결 방법 :

    • dp를 활용해 문제 해결
    • maze[i][j] = 왼쪽 위, 왼쪽, 위 세 값 중 큰 값 + maze[i][j]
    • 이를 위해 maze에 padding 추가
  • 회고 :

    • padding 추가할 때 첫 row를 추가하기 위해 unshift()를 사용했는데 뭔가 더 좋은 방법이 있을 것 같다…
  • 코드

    const fs = require('fs');
    const filePath = process.platform === 'linux' ? '/dev/stdin' : '../input.txt';
    const input = fs.readFileSync(filePath).toString().trim();
    
    solution(input);
    
    function solution(props) {
      props = props.split('\n');
      const [N, M] = props[0].split(' ').map((e) => +e);
    
      const maze = props
        .slice(1)
        .map((e) => e.split(' ').map((ele) => +ele))
        .map((e) => [0, ...e]);
      maze.unshift(Array(M + 1).fill(0));
    
      for (let i = 1; i <= N; i++) {
        for (let j = 1; j <= M; j++) {
          maze[i][j] = Math.max(maze[i - 1][j], maze[i][j - 1], maze[i - 1][j - 1]) + maze[i][j];
        }
      }
    
      console.log(maze[N][M]);
    }
    
  • 출처: 백준