[배열 회전 - Medium]

< 문제 >

  • 개요
    [ 5*5(2차원배열)을 90도 회전하는 로직 ] a 배열을 90도 회전하여 b배열에 넣고 다시 b배열을 90도 회전하여 a에 넣어서 180도 회전된 배열을 출력하기 (10분)

  • 예상 결과
    예상 결과는 하기 코드 실행시 예상되는 결과 값이다.

 - 최초 a배열 준비
  1 	2 	3 	4 	5 
  6 	7 	8 	9 	10
  11 	12 	13 	14 	15
  16	17	18	19	20
  21	22	23	24	25
  
  - 90 회전
  5	10	15	20	25
  4	9	14	19	24
  3	8	13 	18	23
  2	7	12	17	22
  1	6	11	16	21
  
  - 180 회전
  25	24	23	22	21
  20	19	18	17	16
  15	14	13	12	11
  10	9	8	7	6
  5	4	3	2	1

< 정답풀이 >

 public class Test05 {

	public static void main( String[] args ) {
		// 시작시간 기록
		long startTime = System.currentTimeMillis();

		// STEP 1. 배열선언
		int a[][] = new int[5][5]; // 초기배열
		int b[][] = new int[5][5]; // 90도 회전결과 배열

		// STEP 2. 처리 및 출력
		process( a, b );

		// 종료시간 기록
		long endTime = System.currentTimeMillis() - startTime;
		System.out.println( "소요시간 : " + endTime + "ms." );
	}

	/**
	  * 
	 * <PRE>
	 * 2차원 배열을 90도, 180도 회전하여 출력하기
	 * </PRE>
	 * 
	 * @param a : 최초 배열
	 * @param b : 이동할 배열
	 */
	public static void process( int[][] a, int[][] b ) {
		int size = a.length;
		int row, col;
		int i = 1;

		// step1. 배열 생성
		for ( row = 0 ; row < size ; row++ ) {
			for ( col = 0 ; col < size ; col++ ) {
				a[row][col] = i++;
			}
		}
		printArray( a );

		// step2. 90도 회전
		turnLeft( a, b );
		printArray( b );

		// step3. 180도 회전
		turnLeft( b, a );
		printArray( a );
	}

	/**
	 * 
	 * <PRE>
	 * 배열을 왼쪽으로 회전시켜서 저장한다.
	 * </PRE>
	 * 
	 * @param a : 기존배열
	 * @param b : 변경될 배열
	 */
	public static void turnLeft( int[][] a, int[][] b ) {
		int size = a.length;
		int row, col;
		for ( row = 0 ; row < size ; row++ ) {
			for ( col = 0 ; col < size ; col++ ) {
				b[row][col] = a[col][size - 1 - row];
			}
		}
	}

	/**
	 * 
	 * <PRE>
	 * 배열을 출력한다.
	 * </PRE>
	 * 
	 * @param arr 배열
	 */
	public static void printArray( int[][] arr ) {
		int size = arr.length;
		for ( int row = 0 ; row < size ; row++ ) {
			for ( int col = 0 ; col < size ; col++ ) {
				System.out.printf( "%3d", arr[row][col] );
			}
			System.out.println();
		}
		System.out.println();
	}
}