본문 바로가기

알고리즘/프로그래머스

[프로그래머스] 2021 dev-matching - 행렬 테두리 회전하기 [JAVA]

문제링크 : programmers.co.kr/learn/courses/30/lessons/77485

 

코딩테스트 연습 - 행렬 테두리 회전하기

6 6 [[2,2,5,4],[3,3,6,6],[5,1,6,3]] [8, 10, 25] 3 3 [[1,1,2,2],[1,2,2,3],[2,1,3,2],[2,2,3,3]] [1, 1, 5, 3]

programmers.co.kr

머리가 안돌아가서 혼났다. 인덱스를 잘 생각해서 회전시키는 문제다

class Solution {
    public static void show(int arr[][]){
		System.out.println();
		for(int i=0;i<arr.length;i++){
			for(int j=0;j<arr[i].length;j++){
				System.out.print(arr[i][j]+ " ");
			}
			System.out.println();
		}
	}
	public static int rotate(int arr[][], int []query){
		int ret = 987654321;
		int tempArr[][] = new int[query[2]-query[0]+1][query[3]-query[1]+1];
		
		tempArr[0][0] = arr[query[0]+1][query[1]];
		tempArr[query[2]-query[0]][0] = arr[query[2]][query[1]+1];
		for(int i=query[1]+1;i<=query[3];i++){
			tempArr[0][i-query[1]] = arr[query[0]][i-1];
			tempArr[query[2]-query[0]][i-query[1]-1] = arr[query[2]][i];
		}
		
		for(int i=query[0]+1;i<=query[2];i++){
			tempArr[i-query[0]][query[3]-query[1]] = arr[i-1][query[3]];
			tempArr[i-query[0]-1][0] = arr[i][query[1]];
		}
		for(int i=0;i<tempArr.length;i++){
			for(int j=0;j<tempArr[i].length;j++){
				if(tempArr[i][j]==0) continue;
				ret = Math.min(ret, tempArr[i][j]);
				arr[i+query[0]][j+query[1]] = tempArr[i][j];
			}
		}
//		show(arr);
		return ret;
	}
	
	public static int[] solution(int rows, int columns, int[][] queries) {
        int[] answer = new int[queries.length];
        int [][]arr = new int[rows+1][columns+1];
        int idx = 1;
        for(int i=1;i<=rows;i++){
        	for(int j=1;j<=columns;j++){
        		arr[i][j] = idx++;
        	}
        }
        for(int i=0;i<queries.length;i++){
        	int query[] = queries[i];
        	answer[i] = rotate(arr,query);
        }
        return answer;
    }
}