Jakorithm
article thumbnail
728x90

문제

https://www.codetree.ai/training-field/search/problems/function-outputs-numeric-square?&utm_source=clipboard&utm_medium=text

 

코드트리 | 코딩테스트 준비를 위한 알고리즘 정석

국가대표가 만든 코딩 공부의 가이드북 코딩 왕초보부터 꿈의 직장 코테 합격까지, 국가대표가 엄선한 커리큘럼으로 준비해보세요.

www.codetree.ai

 

 

정수 n이 주어지면, n * n 크기의 숫자 사각형을 출력하는 함수를 만들어 출력하는 프로그램을 작성해 보세요.

 

입력 예시

4

 

출력 예시

1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16

 

 

코드

첫 번째 줄에 정수 n이 주어진다.

  • 1 <= n <= 20
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        int[][] matrix = square(new int[n][n]);
        printMatrix(matrix);
    }

    // n * n 배열에 숫자 담기
    private static int[][] square(int[][] arr) {
        int count = 1;

        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr.length; j++) {
                arr[j][i] = count;
                count++;
            }
        }

        return arr;
    }

    // n * n 배열 출력하기
    private static void printMatrix(int[][] arr) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr.length; j++) {
                sb.append(arr[i][j]).append(" ");
            }
            sb.append("\n");
        }

        System.out.println(sb);
    }
}

 

728x90