[프로그래머스 / Level2] 행렬 테두리 회전하기 (Java)

wannabeking·2022년 6월 10일
0

코딩테스트

목록 보기
14/155

문제 보기



사용한 것

  • rows, columns 크기의 행렬 matrix
  • rotate(): 행렬을 시계방향으로 회전하고 최솟값 반환
    • Queue 사용하여 구현


풀이 방법

  • rows, columns 크기의 행렬을 생성하고 1부터 차례대로 넣어 줌
  • queries.length 크기의 int 배열 answer 생성하고 answer.length 만큼 for문 돌림
  • for문에서 answer[i]에 rotate(matrix, queries[i]) 결과값을 넣어 줌
  • rotate()는 첫 4개의 for문에서 matrix 테두리의 숫자를 queue에 넣어 줌
  • 다 넣어 줬으면 queue의 최솟값을 min으로 저장
  • 시계방향으로 회전시키기 위해 한칸 밀어서 4개의 for문으로 queue 원소를 matrix에 넣어주고 min 반환
  • answer 반환


코드

import java.util.LinkedList;
import java.util.Queue;

class Solution {

    public int[] solution(int rows, int columns, int[][] queries) {
        int[][] matrix = new int[rows][columns];
        int num = 1;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                matrix[i][j] = num++;
            }
        }

        int[] answer = new int[queries.length];
        for (int i = 0; i < answer.length; i++) {
            answer[i] = rotate(matrix, queries[i]);
        }
        return answer;
    }

    public int rotate(int[][] matrix, int[] query) {
        Queue<Integer> queue = new LinkedList<>();
        int x1 = query[0] - 1;
        int y1 = query[1] - 1;
        int x2 = query[2] - 1;
        int y2 = query[3] - 1;

        for (int y = y1; y < y2; y++) {
            queue.add(matrix[x1][y]);
        }
        for (int x = x1; x < x2; x++) {
            queue.add(matrix[x][y2]);
        }
        for (int y = y2; y > y1; y--) {
            queue.add(matrix[x2][y]);
        }
        for (int x = x2; x > x1; x--) {
            queue.add(matrix[x][y1]);
        }

        int min = queue.stream()
            .min(Integer::compare)
            .get();

        for (int y = y1 + 1; y <= y2; y++) {
            matrix[x1][y] = queue.remove();
        }
        for (int x = x1 + 1; x <= x2; x++) {
            matrix[x][y2] = queue.remove();
        }
        for (int y = y2 - 1; y >= y1; y--) {
            matrix[x2][y] = queue.remove();
        }
        for (int x = x2 - 1; x >= x1; x--) {
            matrix[x][y1] = queue.remove();
        }

        return min;
    }
}


profile
내일은 개발왕 😎

0개의 댓글