오늘의 학습 키워드
- 시뮬레이션 (Simulation)
- 브루트 포스 (Brute Force) 접근법
- 시간 복잡도와 최적화
문제 이해
이 문제는 격자판에서 주어진 명령에 따라 모든 칸을 이동시키고, 특정 목표 위치 (x, y)
에 도달할 수 있는 경우의 수를 계산하는 문제입니다. 문제의 핵심은 주어진 명령(쿼리)을 반복적으로 적용하여, 특정 위치에 도달할 수 있는지 확인하는 것입니다.
실패한 풀이
class Solution {
public long solution(int n, int m, int x, int y, int[][] queries) {
long answer = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
int[] result = move(i, j, n, m, queries);
if (isDestination(result, x, y)) {
answer++;
}
}
}
return answer;
}
public int[] move(int startX, int startY, int n, int m, int[][] queries) {
int currentX = startX;
int currentY = startY;
for (int i = 0; i < queries.length; i++) {
int direction = queries[i][0];
int distance = queries[i][1];
switch (direction) {
case 0: // 왼쪽
currentY = Math.max(0, currentY - distance);
break;
case 1: // 오른쪽
currentY = Math.min(m - 1, currentY + distance);
break;
case 2: // 위쪽
currentX = Math.max(0, currentX - distance);
break;
case 3: // 아래쪽
currentX = Math.min(n - 1, currentX + distance);
break;
}
}
return new int[]{currentX, currentY};
}
public boolean isDestination(int[] location, int x, int y) {
return location[0] == x && location[1] == y;
}
}
풀이 설명
이동 시뮬레이션
- 주어진 격자판의 모든 칸에 대해 시뮬레이션을 수행합니다.
- 각 칸에서 주어진 쿼리(명령)을 차례로 적용하여 최종 위치를 계산합니다.
결과 검증
- 시뮬레이션을 통해 계산된 최종 위치가 목표 위치
(x, y)
와 일치하는지 확인합니다. - 일치하는 경우의 수를 세어 반환합니다.
- 시뮬레이션을 통해 계산된 최종 위치가 목표 위치
'알고리즘 공부' 카테고리의 다른 글
99클럽 코테 스터디 29일차 TIL (0) | 2024.08.19 |
---|---|
99클럽 코테 스터디 28일차 TIL (0) | 2024.08.18 |
99클럽 코테 스터디 26일차 TIL (0) | 2024.08.16 |
99클럽 코테 스터디 25일차 TIL (0) | 2024.08.15 |
99클럽 코테 스터디 24일차 TIL (0) | 2024.08.15 |