[알고리즘] 숫자 배열 회전

2024. 1. 1. 19:08알고리즘 풀이/Java

나의 풀이

- 자바에서는 C와 다르게 배열을 초기화할때 변수를 넣어줘도 런타임 에러가 나지 않는다는 것을 배웠다.

- 자바에서도 파이썬과 마찬가지로 배열 a = b로 만들고 b의 인덱스에 해당하는 값을 바꿔도 a의 값도 바뀐다는 것을 배웠다.

- clone 메소드를 이용하면 2차원 배열의 경우 얕은 복사로 된다는 것을 배웠다.

- 2차원 배열 깊은 복사를 하려면 Arrays.copyOf(original[i], cols)와 같이 Arrays.copyOf를 사용한다는 것을 배웠다.

import java.util.Scanner;
import java.io.FileInputStream;

class Solution
{
	public static void main(String args[]) throws Exception
	{
		Scanner sc = new Scanner(System.in);
		int T;
		T=sc.nextInt();

		for(int test_case = 1; test_case <= T; test_case++)
		{
            int n = sc.nextInt();
            int[][] graph = new int[n][n];
            for (int i = 0; i < n; i++) {
            	for (int j = 0; j < n; j++) {
                	graph[i][j] = sc.nextInt();    
                }
            }
            
            int[][] rotated90 = rotate(graph);
            int[][] rotated180 = rotate(rotated90);
            int[][] rotated270 = rotate(rotated180);
            
            System.out.println("#" + test_case);
            for (int i = 0; i < n; i++) {
                printRow(rotated90[i]);
                System.out.print(" ");
                printRow(rotated180[i]);
                System.out.print(" ");
                printRow(rotated270[i]);
                System.out.println();
            }
		}
	}
    
    private static int[][] rotate(int[][] graph)
    {	
        int n = graph.length;
        int[][] rotatedGraph = new int[n][n];
        for (int i = 0; i < n; i++) {
        	for (int j = 0; j < n; j++) {
            	    rotatedGraph[j][n-i-1] = graph[i][j];
            }
        }
        return rotatedGraph;
    }
    
    private static void printRow(int[] graph) {
    	for (int i = 0; i < graph.length; i++) {
        	System.out.print(graph[i]);
        }
    }
}

 

https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV5Pq-OKAVYDFAUq

 

SW Expert Academy

SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!

swexpertacademy.com