[Programmers]-행렬 테두리 회전하기

문제

코드

import java.util.*;

class Solution {
    public int[] solution(int rows, int columns, int[][] queries) {
        int[] answer = new int[queries.length];

        int[][] arr = new int[rows][columns];
        int cnt = 1;

        for(int i=0;i<rows;i++){
            for(int j=0;j<columns;j++){
                arr[i][j] = cnt++;     
            }
        }


        ArrayList<Integer> list = new ArrayList<Integer>();

        for(int i=0;i<queries.length;i++){
            int x1 = queries[i][0];
            int y1 = queries[i][1];
            int x2 = queries[i][2];
            int y2 = queries[i][3];

            int x = x1;
            int y = y1-1;

            //바뀐 숫자들 배열에 담기
            list.add(arr[x][y]);
            while(y != y2){//오른쪽으로
                y++;
                list.add(arr[x-1][y-1]);
            }
            while(x != x2){//아래로
                x++;
                list.add(arr[x-1][y-1]);
            }
            while(y != y1){//왼쪽으로
                y--;
                list.add(arr[x-1][y-1]);
            }
            while(x != x1+1){//위로
                x--;
                list.add(arr[x-1][y-1]);
            }
            list.remove(list.size()-1);

            //배열에 담은 숫자 행렬에 넣기
            x = x1;
            y = y1-1;
            int k = 0;
            while(y != y2){//오른쪽으로
                y++;
                arr[x-1][y-1] = list.get(k++);
            }
            while(x != x2){//아래로
                x++;
                arr[x-1][y-1] = list.get(k++);
            }
            while(y != y1){//왼쪽으로
                y--;
                arr[x-1][y-1] = list.get(k++);
            }
            while(x != x1+1){//위로
                x--;
                arr[x-1][y-1] = list.get(k++);
            }

            Collections.sort(list);
            answer[i] = list.get(0);
            list.clear();
        }

        return answer;
    }
}

코드 설명

문제를 너무 빨리 풀려다보니 실행속도가 너무 느려졌다. 조금더 신중하게 짜보자.

요약

  • 조금 빠를줄 알았지만 크기가 커지니 너무 느려졌다.