본문 바로가기
Algorithm/Programmers

[프로그래머스] 방문 길이 (Level 3)

by 잭피 2020. 11. 18.

programmers.co.kr/learn/courses/30/lessons/49994

 

코딩테스트 연습 - 방문 길이

 

programmers.co.kr


문제

(0,0)부터 시작한다

  • U: 위쪽으로 한 칸 가기

  • D: 아래쪽으로 한 칸 가기

  • R: 오른쪽으로 한 칸 가기

  • L: 왼쪽으로 한 칸 가기

위와 같은 규칙으로 움직인다 (input : ULURRDLLU)

이동한 길의 개수를 출력하는 문제이다

(하지만, 한번 이동했던 길은 카운트하지 않는다) 

 

해결

Enum 클래스에 각 규칙의 좌표를 정의한다 

Graph 클래스에는 Point(좌표) 클래스와 Set을 필드로 둔다

그리고 move()라는 메소드를 통해 좌표를 움직인다

start, end 객체를 생성하고 Set에 넣는다

(여기서 좌표는 최대 -5 < x,y < 5 이므로 Math.abs() 메소드로 조건을 검사한 후 넘지않도록 한다)

(넘어가는경우는 계산을 하지 않는다)

그리고 start와 end가 서로 같은 경우는 제외해준다

최종적으로 set의 size를 출력한다

public class programmers_방문길이_js {
    public static int solution(String dirs) {
        Graph graph = new Graph();
        for (char dir : dirs.toCharArray()) graph.move(dir);
        System.out.println(graph.distanceSet);
        return graph.distanceSet.size();
    }

    static class Graph {
        Point point;
        Set<Set<Point>> distanceSet;

        public Graph() {
            point = new Point(0,0);
            this.distanceSet = new HashSet<>();
        }

        public void move(char location) {
            Point start = new Point(this.point.x, this.point.y);
            this.point.x += Math.abs(this.point.x + Location.findByLocation(location).x) > 5 ? 0 : Location.findByLocation(location).x;
            this.point.y += Math.abs(this.point.y + Location.findByLocation(location).y) > 5 ? 0 : Location.findByLocation(location).y;
            Point end = new Point(this.point.x, this.point.y);
            Set<Point> historySet = new HashSet<>();
            historySet.add(start);
            historySet.add(end);
            if (!(start.x == end.x && start.y == end.y)) distanceSet.add(historySet);
        }
    }

    static class Point {
        int x;
        int y;

        public Point(int x, int y) {
            this.x = x;
            this.y = y;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            Point point = (Point) o;

            if (x != point.x) return false;
            return y == point.y;
        }

        @Override
        public int hashCode() {
            int result = x;
            result = 31 * result + y;
            return result;
        }
    }

    enum Location {
        U('U', 0,1),
        D('D',0,-1),
        R('R',1,0),
        L('L',-1,0);

        char name;
        int x;
        int y;

        Location(char name, int x, int y) {
            this.name = name;
            this.x = x;
            this.y = y;
        }

        static Location findByLocation(char name) {
            return Arrays.stream(Location.values())
                    .filter(location -> location.name == name)
                    .findAny().orElseThrow();
        }
    }
}

댓글