문제풀이/자료구조

[Javascript/자바스크립트] (프로그래머스) 방문 길이

딜레이레이 2025. 5. 16. 17:01

https://school.programmers.co.kr/learn/courses/30/lessons/49994

코드

function solution(dirs) {
  let answer = 0;
  const direction = {
    U: [-1, 0],
    D: [1, 0],
    R: [0, 1],
    L: [0, -1],
  };
  let position = [0, 0];
  const visited = new Set();
  for (const d of dirs) {
    const [x, y] = position;
    const nx = position[0] + direction[d][0];
    const ny = position[1] + direction[d][1];

    if (nx < -5 || nx > 5 || ny < -5 || ny > 5) continue;
    if (
      !visited.has([x, y, nx, ny].join("_")) &&
      !visited.has([nx, ny, x, y].join("_"))
    ) {
      visited.add([x, y, nx, ny].join("_"));
      answer++;
    }
    position = [nx, ny];
  }

  return answer;
}

 

한 번 지나갔던 길은 집합에 저장하여 표시해둔다. (a,b)에서 (c,d)로 이동한 경우에는 집합에 `"a_b_c_d"` 형태로 저장한다. (자바스크립트의 집합(Set)은 객체를 참조로 비교하기 때문에 같은 내용을 갖고 있는 경우라도 다른 메모리 위치에 저장되어 있다면 다른 객체로 본다. 그렇기 때문에 객체로 저장하면 같은 내용을 갖고 있는 값이 중복 저장될 수도 있다.)