본문 바로가기

코딩테스트/programmers

방문 길이

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

체크해야하는 건 방문한 '길'의 개수이지, 좌표가 아니다.

처음엔 좌표인 줄 알고 계속 답이 안나와서... 한참 고민했다.

 

좌표와는 다르게 방문했던 '길'은 좌에서 우로 이동한 경우나, 우에서 좌로 이동한 경우가 같은 '길'이므로 중복체크를 해야한다.

 

그래서 애당초 캐싱할 때 좌->우 케이스와 우->좌 케이스를 같이 집어넣었다.

 

import java.util.*;

class Solution {
    
    public int solution(String dirs) {
        HashSet<String> cache = new HashSet();
        
        int[] curr = {5, 5};
        
        int cnt = 0;
        
        String[] split = dirs.split("");
        for (String s : split) {
            
            int[] moved = DIR.move(s, curr);
            if (moved[0] < 0 || moved[0] > 10 || moved[1] < 0 || moved[1] > 10) continue;
            
            String f = "" + curr[0] + curr[1] + moved[0] + moved[1];
            
            if (!cache.contains(f)) {
                cnt++;
            }
            
            cache.add(f);
            
            String r = "" + moved[0] + moved[1] + curr[0] + curr[1];
            cache.add(r);
            
            curr = moved;
            
        }
        
        return cnt;
    }
    
    enum DIR {
        U(1, 0), D(-1, 0), R(0, 1), L(0, -1);
        int y;
        int x;
        DIR(int y, int x) {
            this.y = y;
            this.x = x;
        }
        static int[] move(String dir, int[] curr) {
            int[] moved = {curr[0], curr[1]};
            DIR d = DIR.valueOf(dir);
            moved[0] += d.y;
            moved[1] += d.x;
            return moved;
        }
    }
}

'코딩테스트 > programmers' 카테고리의 다른 글

스킬트리  (0) 2023.10.28
주식가격  (0) 2023.10.25
땅따먹기  (0) 2023.10.25
주차 요금 계산  (0) 2023.10.25
더 맵게  (0) 2023.10.23