[프로그래머스] 코딩테스트 연습 - 그래프 Level 5 방의 개수

uoahy·2021년 9월 24일
0
post-thumbnail

Solution.java

import java.util.*;

class Solution {    
    public int solution(int[] arrows) {
        int answer = 0;
        
        int[][] d = { { 0, 1 }, { 1, 1 }, { 1, 0 }, { 1, -1 }, { 0, -1 }, { -1, -1 }, { -1, 0 }, { -1, 1 } };
        
        HashSet<Coordinate> hs1 = new HashSet<>();
        HashSet<Edge> hs2 = new HashSet<>(); 
        
        int x = 0;
        int y = 0;
        hs1.add(new Coordinate(x, y));
        for (int arrow : arrows) {
            for (int i = 0; i < 2; i++) {
                int next_x = x + d[arrow][0];
                int next_y = y + d[arrow][1];
                
                if (hs1.contains(new Coordinate(next_x, next_y)) && !hs2.contains(new Edge(new Coordinate(x, y), new Coordinate(next_x, next_y)))) {
                    answer++;
                }
                
                Coordinate tmp = new Coordinate(next_x, next_y);
                hs1.add(new Coordinate(next_x, next_y));
                hs2.add(new Edge(new Coordinate(x, y), new Coordinate(next_x, next_y)));
                hs2.add(new Edge(new Coordinate(next_x, next_y), new Coordinate(x, y)));
                
                x = next_x;
                y = next_y;
            }
        }
        
        return answer;
    }
}

class Coordinate {
    int x, y;
    
    Coordinate(int x, int y) {
        this.x = x;
        this.y = y;
    }
    
    public boolean equals(Object o) {
        Coordinate c = (Coordinate) o;
        return this.x == c.x && this.y == c.y;
    }
    
    public int hashCode() {
        int result = x;
        result = 31 * result + y;
        return result;
    }
}

class Edge {
    Coordinate from, to;
    
    Edge(Coordinate from, Coordinate to) {
        this.from = from;
        this.to = to;
    }
    
    public boolean equals(Object o) {
        Edge e = (Edge) o;
        return this.from.x == e.from.x && this.from.y == e.from.y && this.to.x == e.to.x && this.to.y == e.to.y;
    }
    
    public int hashCode() {
        int result = from.x;
        result = 31 * result + from.y;
        result = 31 * result + to.x;
        result = 31 * result + to.y;
        return result;
    }
}

다른 분의 풀이를 보고 아이디어를 얻어 풀었다.

equals와 hashCode를 오버라이딩하는법을 배울 수 있었다.

출처: 프로그래머스 코딩 테스트 연습, https://programmers.co.kr/learn/challenges

0개의 댓글