Skip to content

Commit 8fdcde7

Browse files
feat: implement matrix operations logic (rotate and shiftRow)
- Implemented rotate: rotates the outer layer of the matrix clockwise - Implemented shiftRow: shifts all rows downward by one - Separated col1, col2, and rows for better performance and clearer logic - Iterated over operations array to apply each command - Assembled final matrix using getAnswer() for output
1 parent 7ad3104 commit 8fdcde7

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
package com.algorithm2025.backjoon2;
2+
3+
import java.util.ArrayDeque;
4+
import java.util.LinkedList;
5+
6+
public class Sample20250519_Q1186 { //코딩테스트 연습 2022 KAKAO TECH INTERNSHIP 행렬과 연산
7+
8+
int r, c;
9+
ArrayDeque<Integer> col1, col2;
10+
LinkedList<ArrayDeque<Integer>> rows;
11+
12+
private void init(int[][] rc) {
13+
r = rc.length;
14+
c = rc[0].length;
15+
16+
col1 = new ArrayDeque<>();
17+
col2 = new ArrayDeque<>();
18+
for (int i = 0; i < r; i++) {
19+
col1.add(rc[i][0]);
20+
col2.add(rc[i][c-1]);
21+
}
22+
23+
rows = new LinkedList<>();
24+
for (int i = 0; i < r; i++) {
25+
ArrayDeque<Integer> tmp = new ArrayDeque<>();
26+
for (int j = 1; j < c-1; j++) {
27+
tmp.add(rc[i][j]);
28+
}
29+
rows.add(tmp);
30+
}
31+
}
32+
33+
private int[][] getAnswer() {
34+
int[][] ans = new int[r][c];
35+
for (int i = 0; i < r; i++) {
36+
ans[i][0] = col1.pollFirst();
37+
ans[i][c-1] = col2.pollFirst();
38+
}
39+
int i = 0;
40+
for (ArrayDeque<Integer> row : rows) {
41+
for (int j = 1; j < c-1; j++) {
42+
ans[i][j] = row.pollFirst();
43+
}
44+
i++;
45+
}
46+
return ans;
47+
}
48+
49+
private void rotate() {
50+
if (c == 2) {
51+
col2.addFirst(col1.pollFirst());
52+
col1.addLast(col2.pollLast());
53+
return;
54+
}
55+
rows.peekFirst().addFirst(col1.pollFirst());
56+
col2.addFirst(rows.peekFirst().pollLast());
57+
rows.peekLast().addLast(col2.pollLast());
58+
col1.addLast(rows.peekLast().pollFirst());
59+
}
60+
61+
private void shiftRow() {
62+
rows.addFirst(rows.pollLast());
63+
col1.addFirst(col1.pollLast());
64+
col2.addFirst(col2.pollLast());
65+
}
66+
67+
public int[][] Sample20250519_Q1186(int[][] rc, String[] operations) {
68+
init(rc);
69+
for (String op : operations) {
70+
switch (op.charAt(0)) {
71+
case 'R' : rotate(); break;
72+
case 'S' : shiftRow(); break;
73+
}
74+
}
75+
return getAnswer();
76+
}
77+
}

0 commit comments

Comments
 (0)