- 배열 / 해시테이블 문제
- 문제분석
1. int[] command : 입력한 커맨드를 나타낸다. 양수일 경우 증가값, -1 일 경우 left, -2 일 경우 right 로 방향을 변경한다.
2. int[][] obstacles : 장애물의 위치를 나타낸다. command 의 입력값대로 로봇을 움직이다가 장애물을 만나면, 해당 위치에서 멈춘다.
3. 주어진 커맨드값과 장애물 값대로 로보트를 움직이다가., 가장 멀리까지 간 위치의 x^2 + y^2 (유클리트 합 ) 를 구하여라
- 문제풀이
1. command 를 분석한다. 동서남북 4 방향을 x,y 값으로 구하기 위해 다음과 같이 방향 값을 정의한다.
1-1. int[][] directions = {{1,0},{0,1},{-1,0},{0,-1}};
1-2. 순서대로 North, East, South, West 값이며, directions[i][0] => North, directions[i][1] => East.. 로 정의할 수 있다.
1-3. 해당 값으로 정의하는 가장 큰 이유는 command 입력값의 -1, -2 값에 따라 left, right 을 turn 한 값을 구하기 위함이다.
1-4. 예를 들어 최초 값 North (1,0) 일때, left (command : -1 ) 이면 directions[i][0+1] 값으로 East(1,0) 이 된다.
1-5. right( command : -2 ) 일경우에는 North(1,0) -> directions[i][0-1] 이다. 이때는 directions 의 왼쪽으로 움직여 West(0,-1) 이 출력되도록한다.
1-6. 해당 directions을 움직이기 위해 int direct = 0 를 정의하며 -1: direct = (direct + 1)%4, -2: direct = (direct + 3)%4 이다.
2. obstacles 를 분석한다.
2-1. 장애물의 위치를 확인하기 위해 Set<String> 함수로 int[][] obstacles 값을 x+","+y 값으로 저장해둔다.
2-2. 이후 command 를 반복하면서 x+","+y 값에 맞딱뜨렸을 경우 해당 값에 멈추도록한다.
public int robotSim(int[] commands, int[][] obstacles) {
int[][] direction = {{0,1},{1,0},{0,-1},{-1,0}};
int max = 0;
Set<String> set = new HashSet<>();
for(int[] ob : obstacles) {
set.add(ob[0]+","+ob[1]);
}
int x = 0;
int y = 0;
int direct = 0;
for (int command : commands) {
if (command == -1) {
direct = (direct+1)%4;
} else if (command == -2) {
direct = (direct+3)%4;
} else {
for (int i = 0; i < command; i++) {
int nx = x + direction[direct][0];
int ny = y + direction[direct][1];
if (set.contains(nx+","+ny)) {
break;
}
x = nx;
y = ny;
max = Math.max(max, x*x+y*y);
}
}
}
return max;
}
'TIL' 카테고리의 다른 글
[코테연습] 2220. Minimum Bit Flips to Convert Number (1) | 2024.09.11 |
---|---|
[코테연습] 2326. Spiral Matrix IV (0) | 2024.09.09 |
[코테연습] 1894. Find the Student that Will Replace the Chalk (0) | 2024.09.02 |
[코테연습] 야근 지수 (0) | 2024.08.30 |
[코테연습] 947. Most Stones Removed with Same Row or Column (0) | 2024.08.29 |