코딩테스트/Java

(프로그래머스) 행렬 테두리 회전하기

SK_MOUSE 2021. 7. 20. 13:32

테두리를 따라서 회전하는 문제이다.

이전에 백준에서 풀었던 미세먼지안녕!문제와 비슷한 원리이다.

2021.05.24 - [분류 전체보기] - [JAVA] 백준 미세먼지 안녕!

 

[JAVA] 백준 미세먼지 안녕!

구현에 관한 문제이다. 완전탐색 방식으로 구현하였다. 아래 예시는 확산+클리너를 1회 작동하였을때 예시이다. import java.util.*; import java.io.*; class Main { static int Row, Col, T; static int[][]..

skmouse.tistory.com

 

필자는 주로 회전을 시킬때 Queue에 담아서 FIFO방식을 이용하여 회전한다.

swap보다는 위 방식이 편하다고 생각한다.

 

하지만 swap방식도 연습해야 할 필요성을 느낀다.

import java.io.*; import java.util.*; class Solution { ​​​​static int[][] table; ​​​​static int minVal; ​​​​public int[] solution(int rows, int columns, int[][] queries) { ​​​​​​​​table = new int[rows + 1][columns + 1]; ​​​​​​​​int count = 0; ​​​​​​​​for (int i = 1; i < rows + 1; i++) { ​​​​​​​​​​​​for (int j = 1; j < columns + 1; j++) { ​​​​​​​​​​​​​​​​++count; ​​​​​​​​​​​​​​​​table[i][j] = count; ​​​​​​​​​​​​} ​​​​​​​​} ​​​​​​​​int[] answer = new int[queries.length]; ​​​​​​​​int i = 0; ​​​​​​​​for (int[] q : queries) { ​​​​​​​​​​​​minVal = 10000; ​​​​​​​​​​​​rotate(q[0], q[1], q[2], q[3]); ​​​​​​​​​​​​answer[i++] = minVal; ​​​​​​​​} ​​​​​​​​return answer; ​​​​} ​​​​static void rotate(int sr, int sc, int er, int ec) { ​​​​​​​​Queue<Integer> q = new LinkedList<>(); ​​​​​​​​q.offer(table[sr][sc]); ​​​​​​​​for (int j = sc + 1; j < ec; j++) {//맨윗줄 ​​​​​​​​​​​​q.offer(table[sr][j]); ​​​​​​​​​​​​table[sr][j] = q.remove(); ​​​​​​​​​​​​minVal = Math.min(minVal, table[sr][j]); ​​​​​​​​} ​​​​​​​​for (int i = sr; i < er; i++) {//우 ​​​​​​​​​​​​q.offer(table[i][ec]); ​​​​​​​​​​​​table[i][ec] = q.remove(); ​​​​​​​​​​​​minVal = Math.min(minVal, table[i][ec]); ​​​​​​​​} ​​​​​​​​for (int j = ec; j > sc; j--) {//하 ​​​​​​​​​​​​q.offer(table[er][j]); ​​​​​​​​​​​​table[er][j] = q.remove(); ​​​​​​​​​​​​minVal = Math.min(minVal, table[er][j]); ​​​​​​​​} ​​​​​​​​for (int i = er; i >= sr; i--) {//좌 ​​​​​​​​​​​​q.offer(table[i][sc]); ​​​​​​​​​​​​table[i][sc] = q.remove(); ​​​​​​​​​​​​minVal = Math.min(minVal, table[i][sc]); ​​​​​​​​} ​​​​} }
반응형