여름의 서재
[프로그래머스] 행렬 테두리 회전하기 (파이썬 & 자바) 본문
728x90
📕 문제
https://programmers.co.kr/learn/courses/30/lessons/77485
💡 풀이법
- Python
def solution(rows, columns, queries):
answer = []
matrix = [[(i-1) * columns + j for j in range(1, columns+1)] for i in range(1, rows+1)]
for q in queries:
x1, y1, x2, y2 = q[0]-1, q[1]-1, q[2]-1, q[3]-1
n = matrix[x1][y1]
min_num = n
x, y = x1, y1
while y < y2:
y += 1
n, matrix[x][y] = matrix[x][y], n
min_num = min(min_num, n)
while x < x2:
x += 1
n, matrix[x][y] = matrix[x][y], n
min_num = min(min_num, n)
while y > y1:
y -= 1
n, matrix[x][y] = matrix[x][y], n
min_num = min(min_num, n)
while x > x1:
x -= 1
n, matrix[x][y] = matrix[x][y], n
min_num = min(min_num, n)
answer.append(min_num)
return answer
print(solution(3, 3, [[1,1,2,2],[1,2,2,3],[2,1,3,2],[2,2,3,3]]))
- Java
class Solution {
static int[][] matrix;
static int minNum;
public int[] solution(int rows, int columns, int[][] queries) {
int[] answer = new int[queries.length];
matrix = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
matrix[i][j] = (i) * columns + j+1;
}
}
for (int i = 0; i < queries.length; i++) {
int x1 = queries[i][0]-1;
int y1 = queries[i][1]-1;
int x2 = queries[i][2]-1;
int y2 = queries[i][3]-1;
int n = matrix[x1][y1];
minNum = n;
int x = x1;
int y = y1;
while (y < y2) {
y++;
n = change(x, y, n);
}
while (x < x2) {
x++;
n = change(x, y, n);
}
while (y > y1) {
y--;
n = change(x, y, n);
}
while (x > x1) {
x--;
n = change(x, y, n);
}
answer[i] = minNum;
}
return answer;
}
static int change(int x, int y, int n) {
int temp = matrix[x][y];
matrix[x][y] = n;
minNum = Math.min(minNum, temp);
return temp;
}
}
'알고리즘 > 프로그래머스' 카테고리의 다른 글
[프로그래머스] 다단계 칫솔 판매 (파이썬) (0) | 2021.12.17 |
---|---|
[프로그래머스] 배달 (파이썬) (0) | 2021.12.17 |
[프로그래머스] 튜플 (파이썬 & 자바) (0) | 2021.12.10 |
[프로그래머스] 가장 먼 노드 (파이썬 & 자바) (0) | 2021.12.08 |
[프로그래머스] 기능개발 (파이썬 & 자바) (0) | 2021.12.08 |
Comments