[leetcode / easy] 1260. Shift 2D Grid - (math, mod && div) (Java)
[리트코드] 1260. Shift 2D Grid 문제를 Java를 사용해 Math로 풀었습니다.
[leetcode / easy] 1260. Shift 2D Grid
🙋♂️ 들어가며
문제를 읽어보면 각 원소들이 K만큼 이동하여 완전탐색할때와 같은 동작방식으로 자리가 바뀌고 있다.
조건을 보니 행, 열 <= 50 이라 $O(N^2)$ 이 가능하다고 판단하였고 이에 다음과 같은 코드를 작성하였다
✅ 정답 코드 (2차원 bruteforce)
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
class Solution {
public List<List<Integer>> shiftGrid(int[][] grid, int k) {
int row = grid.length;
int col = grid[0].length;
// 1. 정답배열
List<List<Integer>> result = new ArrayList<>();
for (int r = 0; r < row; r++) {
List<Integer> temp = new ArrayList<>();
for (int c = 0; c < col; c++) {
temp.add(0);
}
result.add(temp);
}
// 2. 모든 원소들을 새로운 자리로 배치
for (int r = 0; r < row; r++) {
for (int c = 0; c < col; c++) {
// 2-1. 현재 값, 현재 행, 현재 열
int cur_val = grid[r][c];
int cr = r;
int cc = c;
// 2-2. 몫, 나머지 활용
int nr = cr;
int nc = cc + k;
// 2-3. nc가 col 이상이면 몫제거
if (nc >= col) {
int mod_diff = nc / col;
nr = (cr + mod_diff) % row;
nc %= col;
}
// 2-4. 대입
result.get(nr).set(nc, cur_val);
}
}
return result;
}
}
This post is licensed under CC BY 4.0 by the author.
