(Python, Java) 프로그래머스 - 행렬 테두리 회전하기
in Algorithm on Programmers, Level2
[문제 링크]
Python 풀이
def rotation(graph, query):
for a,b,c,d in query:
x1,y1,x2,y2 = a-1,b-1,c-1,d-1
py = y2
tmp1 = graph[x1][y2]
while py != y1:
graph[x1][py] = graph[x1][py - 1]
py -= 1
px = x2
tmp2 = graph[x2][y2]
while px != x1:
graph[px][y2] = graph[px - 1][y2]
px -= 1
py = y1
tmp3 = graph[x2][y1]
while py != y2:
graph[x2][py] = graph[x2][py + 1]
py += 1
px = x1
while px != x2:
graph[px][y1] = graph[px + 1][y1]
px += 1
graph[x1 + 1][y2] = tmp1
graph[x2][y2 - 1] = tmp2
graph[x2 - 1][y1] = tmp3
def calMin(graph, query):
ls = []
for a, b, c, d in query:
x1, y1, x2, y2 = a - 1, b - 1, c - 1, d - 1
ls.extend(graph[x1][y1:y2 + 1])
ls.extend(graph[x2][y1:y2 + 1])
for x in range(x1, x2 + 1):
ls.append(graph[x][y1])
ls.append(graph[x][y2])
return min(ls)
def solution(rows, columns, queries):
answer = []
graph = [[(j - 1) * columns + i for i in range(1, columns + 1)] for j in range(1, rows + 1)]
for query in queries:
rotation(graph, query)
answer.append(calMin(graph, query))
return answer
분명 최소값을 계산하는 과정과 그래프를 회전하는 과정을 합쳐서 더욱 간단하게 만들 수 있다.
하지만 함수는 한가지 일만 하도록 하기 위해서 분리했다.
Java 풀이
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class Solution {
public int[] solution(int rows, int columns, int[][] queries) {
List<Integer> answer = new ArrayList<>();
int[][] graph = initGraph(rows, columns);
for (int[] query : queries) {
rotate(graph, query);
answer.add(getMinInGraph(graph, query));
}
return answer.stream().mapToInt(Integer::intValue).toArray();
}
private int[][] initGraph(int rows, int columns) {
int[][] graph = new int[rows][columns];
int cnt = 1;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
graph[i][j] = cnt;
cnt++;
}
}
return graph;
}
private void rotate(int[][] graph, int[] query) {
int x1 = query[0] - 1, y1 = query[1] - 1, x2 = query[2] - 1, y2 = query[3] - 1;
int temp1 = graph[x1][y2];
int temp2 = graph[x2][y2];
int px = x1, py = y2;
while (py > y1) {
graph[px][py] = graph[px][py - 1];
py--;
}
px = x2;
py = y2;
while (px > x1) {
graph[px][py] = graph[px - 1][py];
px--;
}
graph[x1 + 1][y2] = temp1;
temp1 = graph[x2][y1];
px = x2;
py = y1;
while (py < y2) {
graph[px][py] = graph[px][py + 1];
py++;
}
graph[x2][y2 - 1] = temp2;
px = x1;
py = y1;
while (px < x2) {
graph[px][py] = graph[px + 1][py];
px++;
}
graph[x2 - 1][y1] = temp1;
}
private Integer getMinInGraph(int[][] graph, int[] query) {
List<Integer> spots = new ArrayList<>();
int x1 = query[0] - 1, y1 = query[1] - 1, x2 = query[2] - 1, y2 = query[3] - 1;
for (int x = x1; x <= x2; x++) {
spots.add(graph[x][y1]);
spots.add(graph[x][y2]);
}
for (int y = y1; y <= y2; y++) {
spots.add(graph[x1][y]);
spots.add(graph[x2][y]);
}
return Collections.min(spots);
}
}