programmers - 행렬 테두리 회전하기

-·2022년 10월 15일
0
import java.util.*;
class Solution {
    public int[] solution(int rows, int columns, int[][] queries) {
        int[] answer = new int[queries.length];
        // 초기 행렬
        int[][] 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++) {
            answer[i] = getMinRotation(matrix, queries[i]);
        }
        return answer;
    }

    public int getMinRotation(int[][] matrix, int[] rotInfo) {
        // 돌리려면 1개는 따로 저장해놔야됨 
        int savePos = matrix[rotInfo[0] - 1][rotInfo[3] - 1];
        int result = matrix[rotInfo[0] - 1][rotInfo[1] - 1];
        // 오른쪽
        int colPosStart = rotInfo[1] - 1;
        int colPosEnd = rotInfo[3] - 1;
        int rowPos = rotInfo[0] - 1;
        for (int i = colPosEnd; i >= colPosStart; i--) {
            if (i > colPosStart) {
                matrix[rowPos][i] = matrix[rowPos][i - 1];
                result = Math.min(result, matrix[rowPos][i]);
            }
        }
        // 위로
        int rowPosStart = rotInfo[0] - 1;
        int rowPosEnd = rotInfo[2] - 1;
        int colPos = rotInfo[1] - 1;
        for (int i = rowPosStart; i <= rowPosEnd; i++) {
            if (i < rowPosEnd) {
                matrix[i][colPos] = matrix[i + 1][colPos];
                result = Math.min(result, matrix[i][colPos]);
            }
        }
        // 왼쪽
        colPosStart = rotInfo[1] - 1;
        colPosEnd = rotInfo[3] - 1;
        rowPos = rotInfo[2] - 1;
        for (int i = colPosStart; i <= colPosEnd; i++) {
            if (i < colPosEnd) {
                matrix[rowPos][i] = matrix[rowPos][i + 1];
                result = Math.min(result, matrix[rowPos][i]);
            }
        }
        // 아래로
        rowPosStart = rotInfo[0] - 1;
        rowPosEnd = rotInfo[2] - 1;
        colPos = rotInfo[3] - 1;
        for (int i = rowPosEnd; i >= rowPosStart; i--) {
            if (i > rowPosStart) {
                matrix[i][colPos] = matrix[i - 1][colPos];
                result = Math.min(result, matrix[i][colPos]);
            }
        }
        // 저장해놓은거 채워주기
        matrix[rotInfo[0]][rotInfo[3] - 1] = savePos;
        return Math.min(result, savePos);
    }
}

이거는 솔직히 그냥 천천히 하니까 되서 어렵지는 않은거 같음

profile
거북이는 오늘도 걷는다

0개의 댓글