본문 바로가기

프로그래머스

프로그래머스 - 방문 길이

import java.util.*;
class Solution {
    public int solution(String dirs) {
        int answer = 0;
        // 중복을 허용하지 않으면 된다!
        Set <String> checkPass = new HashSet<>();
        int x = 0;  
        int y = 0;
        for(int i=0; i<dirs.length(); i++){
           if(dirs.charAt(i) == 'L' && x > -5){
                String first = "(" + x + "," + y + ")"; 
                x--;
                String last =  "(" + x + "," +y + ")";
                String check1 = first + "-" + last;
                String check2 = last + "-" + first;
                if(!checkPass.contains(check1) && !checkPass.contains(check2)){
                    checkPass.add(check1);
                    checkPass.add(check2);
                }
           } 
           if(dirs.charAt(i) == 'R' && x < 5){
                 String first = "(" + x + "," + y + ")"; 
                x++;
                String last =  "(" + x + "," +y + ")";
                String check1 = first + "-" + last;
                String check2 = last + "-" + first;
                if(!checkPass.contains(check1) && !checkPass.contains(check2)){
                    checkPass.add(check1);
                    checkPass.add(check2);
                }
           }
           if(dirs.charAt(i) == 'U' && y < 5){
                 String first = "(" + x + "," + y + ")"; 
                y++;
                String last =  "(" + x + "," +y + ")";
                String check1 = first + "-" + last;
                String check2 = last + "-" + first;
                if(!checkPass.contains(check1) && !checkPass.contains(check2)){
                    checkPass.add(check1);
                    checkPass.add(check2);
                }
           } 
           if(dirs.charAt(i) == 'D' && y > -5){
               String first = "(" + x + "," + y + ")"; 
                y--;
                String last =  "(" + x + "," +y + ")";
                String check1 = first + "-" + last;
                String check2 = last + "-" + first;
                if(!checkPass.contains(check1) && !checkPass.contains(check2)){
                    checkPass.add(check1);
                    checkPass.add(check2);
                }  
           } 
                       
            
        }
        answer = checkPass.size()/2;
        System.out.println(answer);
        return answer;
    }
}