Coding Test Study/Programmers

잡기 놀이

똑똑한망치 2024. 8. 2. 12:22
728x90
반응형

 

풀이 방법

import java.util.*;

class Solution {
    public int solution(int x1, int y1, int x2, int y2) {
        Set<List<Integer>> setA = new HashSet<>();
        Set<List<Integer>> setB = new HashSet<>();
        setA.add(List.of(x1, y1));
        setB.add(List.of(x2, y2));

        Set<List<Integer>> historyA = new HashSet<>(Set.copyOf(setA));
        Set<List<Integer>> historyB = new HashSet<>(Set.copyOf(setB));

        if (x1 == x2 && y1 == y2) {
            return 0;
        }

        int time = 1;

        while (true) {
            Set<List<Integer>> newSetA = new HashSet<>();
            Set<List<Integer>> newSetB = new HashSet<>();

            setA.forEach(valA -> {
                newSetA.add(List.of(valA.get(0) + 1, valA.get(1)));
                newSetA.add(List.of(valA.get(0), valA.get(1) + 1));
                newSetA.add(List.of(valA.get(0) - 1, valA.get(1)));
                newSetA.add(List.of(valA.get(0), valA.get(1) - 1));
            });
            setB.forEach(valB -> {
                newSetB.add(List.of(valB.get(0) + 1, valB.get(1) + 1));
                newSetB.add(List.of(valB.get(0) - 1, valB.get(1) - 1));
                newSetB.add(List.of(valB.get(0) - 1, valB.get(1) + 1));
                newSetB.add(List.of(valB.get(0) + 1, valB.get(1) - 1));
            });

            newSetA.removeAll(historyA);
            newSetB.removeAll(historyB);

            for(List<Integer> posA : newSetA) {
                if(newSetB.contains(posA)) {
                    return time;
                }
            }

            historyA.addAll(newSetA);
            historyB.addAll(newSetB);

            setA = newSetA;
            setB = newSetB;
            time++;
        }
    }
}
반응형

'Coding Test Study > Programmers' 카테고리의 다른 글

아메바 분열  (0) 2024.08.01
마을 판사 찾기  (0) 2024.07.31
[Java] 난이도 - 중 / DP 문제  (0) 2024.03.22
[Java] k 자리 제거하기  (0) 2024.03.22
[Java] 선을 넘나드는 사각형  (1) 2024.03.22