여름의 서재

[프로그래머스] 행렬 테두리 회전하기 (파이썬 & 자바) 본문

알고리즘/프로그래머스

[프로그래머스] 행렬 테두리 회전하기 (파이썬 & 자바)

엉아_ 2021. 12. 13. 16:16
728x90

📕 문제

https://programmers.co.kr/learn/courses/30/lessons/77485

 

코딩테스트 연습 - 행렬 테두리 회전하기

6 6 [[2,2,5,4],[3,3,6,6],[5,1,6,3]] [8, 10, 25] 3 3 [[1,1,2,2],[1,2,2,3],[2,1,3,2],[2,2,3,3]] [1, 1, 5, 3]

programmers.co.kr

 

💡 풀이법

- 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;
    }
}
Comments