Post

[프로그래머스/LV2] 충돌위험 찾기 - queue (Java)

[프로그래머스/LV2] 요격시스템 문제를 Java로 수학을 활용하여 해결한 풀이입니다.

[프로그래머스/LV2] 충돌위험 찾기 - queue (Java)

🙋‍♂️ 들어가며

문제를 보자

테스트케이스 1번 기준,

routes 4 -> 2 이게 points[3] -> points[1] 이라는 것을 알 수 있다.

오호라 1번 로봇이 [1][4] -> [6][4] 로 이동하네

컴퓨터 배열에선 [0][3] -> [5][3] 이겠지만 말이다.

테스트케이스를 다 검증해보니 이 문제는 q를 응용하여 풀 수 있겠더라

최악의 실행시간은

100 * 100 * 200 * 2

routes[i] 길이 * robot길이 * 최악의 r,c 이동거리 * (q 삽입 삭제)

400만 연산으로 충분



이제 내 아이디어는 다음과 같다

함수

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
	1-1. q 생성
	1-2. 각로봇의 첫번째 위치 행열, 목표 위치 행열,  현재위치 idx, 이동할거리, 현재 로봇 idx를 q에 추가 
	
	2. 검사 (while문)
		2-1. 만약 q가 비었으면 종료
		2-2. q가 비지않고 q에 원소가 있다면 -> 현재 q 길이만큼 검사
		2-3. 각 좌표 방문처리
		2-4. 만약 현재좌표가 목표좌표 도달시 -> next_route_idx 값 변환
		2-5. 만약 충돌시 -> 횟수 추가 (중복연산 방지)
		2-6. 만약 next_route_idx 끝점 도달시 종료
		2-7. 끝점은 도달 못했지만, 현재 목표지점 도달시 -> target 좌표 변경	

		2-8. 좌표변경 (행우선, 열 그다음)

		2-9. q에 다시 추가
		(만약 목표 좌표가 바뀌었다면?)
		(그렇지 않고, 목표 좌표가 바뀌지 않았다면?)

	3. 종료



✅ 코드 (queue)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import java.util.Queue;
import java.util.ArrayDeque;


class Solution {
    static int answer;
    
    public int solution(int[][] points, int[][] routes) {
        answer = 0;
        
        // 1. 계산
        my_solver(points, routes);
        
        // 5. 반환
        return answer;
    }
    
    // 2. 함수
    static void my_solver(int[][] points, int[][] routes) {
        
        // 2-1. q 생성
        Queue<int[]> q = new ArrayDeque<>();
        
        // 2-2. 첫번째 routes[i][0] 좌표를 q에 저장
        int N = routes.length;
        for (int i = 0; i < N; i++) {
            int cur_route = routes[i][0]-1;
            int next_route = routes[i][1]-1;
            int sr = points[cur_route][0];
            int sc = points[cur_route][1];
            int target_r = points[next_route][0];
            int target_c = points[next_route][1];
            int route_idx = 0;
            int route_leng = routes[i].length;
            int robot_idx = i;
            
            // 2-3. 시작 r,c 다음 r,c 로봇 idx, 현재 로봇의 방문경로 길이
            q.add(new int[] {sr, sc, target_r, target_c, route_idx+1, route_leng, robot_idx});
        }
        
        // 3. 검사
        while (true) {
            // 3-1. 만약, q 없으면 종료
            if (q.isEmpty()) break;
            int[][] visited = new int[101][101];
            
            // 3-2. 그렇지않고, q에 원소가 있다면
            int cur_size = q.size();
            for (int i = 0; i < cur_size; i++) {
                int[] pos = q.poll();
                
                int cr = pos[0];
                int cc = pos[1];
                int target_r = pos[2];
                int target_c = pos[3];
                int cur_route_idx = pos[4];
                int route_leng = pos[5];
                int cur_robot_idx = pos[6];
                
                // 3-3. 방문 처리
                visited[cr][cc]++;
                
                // 3-4. 만약 현재좌표가 목표좌표 도달시 -> next_route_idx+1
                int next_route_idx = -1;
                
                if (cr == target_r && cc == target_c) {
                    next_route_idx = cur_route_idx + 1;
                }
                
                // 3-5. 만약 충돌시 -> 횟수 추가 (중복연산 방지)
                if (visited[cr][cc] == 2) answer++;
                
                // 3-6. 만약 next_route_idx 끝점 도달시 종료
                if (next_route_idx == route_leng) continue;
                
                // 3-7. 끝점 도달 못했지만, 현재목표지점 도달시 -> target 좌표 변경
                if (next_route_idx != -1) {
                    int[] cur = routes[cur_robot_idx];
                    int next_pos = cur[next_route_idx]-1;
                    target_r = points[next_pos][0];
                    target_c = points[next_pos][1];
                }
                
                // 3-8. 좌표 변경 (행우선, 열 그다음)
                int nr = -1;
                int nc = -1;
                if (cr != target_r) {
                    if (cr < target_r) {
                        nr = cr + 1;
                        nc = cc;
                    }
                    else if (cr > target_r) {
                        nr = cr - 1;
                        nc = cc;
                    }
                }
                else if (cc != target_c) {
                    if (cc < target_c) {
                        nr = cr;
                        nc = cc + 1;
                    }
                    else if (cc > target_c) {
                        nr = cr;
                        nc = cc - 1;
                    }
                }
                
                // 3-9. q에 다시 추가 (조건 2개)
                // 3-9-a. 만약 다음좌표가 바뀌었다면?
                if (next_route_idx != -1) {
                    q.add(new int[] {nr, nc, target_r, target_c, next_route_idx, route_leng, cur_robot_idx});
                }
                // 3-9-b. 만약 다음좌표가 안바뀌었다면?
                else if (next_route_idx == -1) {
                    q.add(new int[] {nr, nc, target_r, target_c, cur_route_idx, route_leng, cur_robot_idx});
                }
                

                
            }
            
        }
        
        
        // 4. 종료
        return;
 
    }
}
This post is licensed under CC BY 4.0 by the author.

Trending Tags

반갑습니다 무엇을 도와드릴까요?