본문 바로가기
알고리즘/프로그래머스

행렬 테두리 회전 (자바)

by 김어찐 2021. 9. 23.
728x90
class Solution {
    public static int[] solution(int rows, int columns, int[][] queries) {
        int[] answer = new int[queries.length];
        int[][] board = new int[rows][columns];
        for (int i = 1; i <=rows*columns ; i++) {
            int r = (i-1)/columns;
            int c = (i-1)%columns;
            board[r][c]=i;
        }
        for (int i = 0; i < queries.length; i++) {
            int minValue = spinBoard(board , queries[i]);
            answer[i]=minValue;
        }
        return answer;
    }

    private static int spinBoard(int[][] board, int[] qry) {

        int[] topLeft = {qry[0]-1,qry[1]-1};
        int[] topRight = {qry[0]-1,qry[3]-1};
        int[] bottomLeft = {qry[2]-1,qry[1]-1};;
        int[] bottomRight = {qry[2]-1,qry[3]-1};;

        int minValue = Integer.MAX_VALUE;

        int x = board[topRight[0]][topRight[1]];

        // 위 이동
        for (int i = topRight[1]-1; i >=topLeft[1] ; i--) {
            int move = board[topRight[0]][i];
            board[topRight[0]][i+1] = move;
            minValue = Math.min(minValue,move);
        }
        // 왼쪽 이동
        for (int i = topLeft[0]+1; i <= bottomLeft[0]; i++) {
            int move = board[i][topLeft[1]];
            board[i-1][topLeft[1]] = move;
            minValue = Math.min(minValue,move);
        }

        //아래 이동
        for (int i =  bottomLeft[1]+1; i <=bottomRight[1] ; i++) {
            int move = board[bottomRight[0]][i];
            board[bottomRight[0]][i-1] = move;
            minValue = Math.min(minValue,move);
        }

        // 오른쪽 이동
        for (int i = bottomRight[0]-1; i >= topRight[0]; i--) {
            int move = board[i][bottomRight[1]];
            board[i+1][bottomRight[1]] = move;
            minValue = Math.min(minValue,move);
        }

        board[topRight[0]+1][topRight[1]] = x;
        minValue = Math.min(minValue,x);
        return minValue;


    }


}
728x90

'알고리즘 > 프로그래머스' 카테고리의 다른 글

프로그래머스 전화번호 목록 (자바)  (0) 2021.09.29
프로그래머스 튜플 (자바)  (0) 2021.09.29
5주차 모음사전 (자바)  (0) 2021.09.14
뉴스 클러스터링 (자바)  (0) 2021.09.12
표편집 (자바)  (0) 2021.09.12