본문 바로가기
Beakjoon&프로그래머스/Java

[프로그래머스/Java] 방문 길이

by 현장 2026. 3. 29.

-Code

import java.util.*;

class Solution {
    static class Pos {
        int row, col;

        public Pos(int row, int col) {
            this.row = row;
            this.col = col;
        }
    }
    static Map<Character, Pos> commPos = Map.of(
            'U', new Pos(1, 0),
            'D', new Pos(-1, 0),
            'R', new Pos(0, 1),
            'L', new Pos(0, -1)
    );

    public int solution(String dirs) {
        int answer = 0;
        int row = 0, col = 0;
        Set<String> route = new HashSet<>();
        for(char dir : dirs.toCharArray()) {
            Pos move = commPos.get(dir);
            int nextRow = row + move.row;
            int nextCol = col + move.col;
            // 각 row, col 위지 string으로 변경
            String start = "" + row + col;
            String end = "" + nextRow + nextCol;
            // 범위 벗어나면 다음 명령어
            if (!isMove(nextRow, nextCol)) {
                continue;
            }
            // 해당 루트가 존재하지 않으면 추가
            if (!route.contains(start + end)) {
                // 정방향과 역방향 모두 추가
                route.add(start + end);
                route.add(end + start);
                // 루트 갯수 증가
                answer++;
            }
            // 위치 변경
            row = nextRow;
            col = nextCol;
        }
        return answer;
    }
    // 범위 탐색
    private boolean isMove(int row, int col) {
        return (-5 <= row && row <= 5) && (-5 <= col && col <= 5);
    }
}

처음에는 boolean의 이중 배열로 방문 처리를 하면서 했으나 이상한 값이 나와서 잘못한 게 무엇인지 찾아보니 지점을 검사하는 것이 아니라 루트(선)를 찾는 문제였고 시작점과 끝점을 저장하는데 역방향도 함께 저장하여 확인하라는 것과 Set을 이용해 보라는 힌트를 보고 해결했습니다.

접근도 그렇고 좀 많은 힌트를 본거같아서 아쉬운 문제였습니다.