Skip to content

Commit afebc6e

Browse files
committed
이예진: [PG] 340211 충돌위험 찾기_241212
1 parent 184ba76 commit afebc6e

File tree

1 file changed

+107
-0
lines changed

1 file changed

+107
-0
lines changed

Programmers/Level2/YJ_340211.java

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
import java.util.*;
2+
// 구현 문제
3+
// FIXME: 테스트케이스 전체는 통과 못해서 오류 수정 중입니다...
4+
public class YJ_340211 {
5+
class Robot {
6+
List<Pos> route;
7+
int start;
8+
int end;
9+
10+
public Robot(int start, int end){
11+
this.route = new ArrayList<>();
12+
this.start = start;
13+
this.end = end;
14+
}
15+
}
16+
17+
class Pos {
18+
int x;
19+
int y;
20+
21+
public Pos(int x, int y) {
22+
this.x = x;
23+
this.y = y;
24+
}
25+
26+
@Override
27+
public boolean equals(Object obj) {
28+
if(obj == null || getClass() != obj.getClass()){
29+
return false;
30+
}
31+
if(this == obj){
32+
return true;
33+
}
34+
Pos pos = (Pos) obj;
35+
return this.x == pos.x && this.y == pos.y;
36+
}
37+
38+
@Override
39+
public int hashCode() {
40+
return Objects.hash(x,y);
41+
}
42+
}
43+
44+
List<Robot> robotList = new ArrayList<>();
45+
public int solution(int[][] points, int[][] routes) {
46+
//초기화
47+
for (int i = 0; i < routes.length; i++) {
48+
int start = routes[i][0] - 1;
49+
int end = routes[i][1] - 1;
50+
robotList.add(new Robot(start, end));
51+
//로봇의 시작위치 저장
52+
int[] point = points[start];
53+
robotList.get(i).route.add(new Pos(point[0], point[1]));
54+
}
55+
//각 로봇들의 모든 이동경로 저장
56+
int longestRoute = 0;
57+
for(Robot robot : robotList){
58+
saveRoute(points, robot);
59+
longestRoute = Math.max(longestRoute, robot.route.size());
60+
}
61+
//경로 충돌 찾기
62+
return findCollision(longestRoute);
63+
}
64+
65+
//모든 로봇의 초 마다 경로를 저장
66+
void saveRoute(int[][] points, Robot robot){
67+
int[] startPoint = points[robot.start];
68+
int[] endPoint = points[robot.end];
69+
70+
//x 좌표 먼저 이동
71+
int x = startPoint[0];
72+
while(x != endPoint[0]){
73+
x = x < endPoint[0] ? x+1 : x-1;
74+
robot.route.add(new Pos(x,startPoint[1]));
75+
}
76+
//y 좌표 이동
77+
int y = startPoint[1];
78+
while(y != endPoint[1]){
79+
y = y < endPoint[1] ? y+1 : y-1;
80+
robot.route.add(new Pos(x,y));
81+
}
82+
}
83+
84+
int findCollision(int longestRoute){
85+
int collision = 0;
86+
87+
for(int i=0; i<longestRoute; i++){
88+
Map<Pos, Integer> map = new HashMap<>();
89+
//i 초동안 움직였을 때 모든 로봇들의 충돌 카운팅
90+
for(Robot robot : robotList){
91+
Pos pos = robot.route.size() > i ? robot.route.get(i) : null;
92+
if(Objects.isNull(pos)){
93+
continue;
94+
}
95+
map.put(pos, map.getOrDefault(pos, 0) + 1);
96+
}
97+
98+
for(Integer count : map.values()){
99+
if(count > 1){
100+
collision++;
101+
}
102+
}
103+
}
104+
105+
return collision;
106+
}
107+
}

0 commit comments

Comments
 (0)