거북이처럼 천천히

알고리즘 (6월 13일) - (2) 본문

Algorithm/알고리즘 문제 풀이

알고리즘 (6월 13일) - (2)

유로 청년 2022. 6. 13. 19:58

1. 문제 (코딩도장, Spiral Array)

https://codingdojang.com/scode/266?answer=28030#answer_28030 

 

코딩도장

프로그래밍 문제풀이를 통해서 코딩 실력을 수련

codingdojang.com


2. 생각

 

6 6이라는 입력을 주면 6 X 6 매트릭스에 나선형 회전을 한 값을 출력해야 한다.

 

  1. m, n 값(m:row, n:column)을 입력 받는다.
  2. m x n 형태의 2차원 Integer Array 생성
  3. 4개의 방향으로 나누어서 switch case 문와 for문을 통해 나선형 형태로 숫자를 정렬
  4. 결과 출력

3. 풀이 및 코드 분석

import java.util.Arrays;
import java.util.Scanner;

public class test {
	
	// 결과 출력
	public static void printResult(int[][] result, int m, int n) {
		System.out.println("Result = ");
		for(int i=0; i<m; i++) {
			for(int j=0;j<n; j++) {
				System.out.printf("%3d",result[i][j]);
			}
			System.out.println();
		}
	}
	
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		
		System.out.print("Spiral Array의 사이즈(m:row, n:column): ");
		int m = scan.nextInt();
		int n = scan.nextInt();
		int [][] result = new int[m][n];
		int count = 0, direction = 0, row=0, column=0;	
		
		while(count<m*n) {
			switch(direction) {
			case 0:
				for(int j=column; j<n-1-column; j++) {
					result[column][j] = count;
					count++;
				}
				direction++;
				break;
			case 1:
				for(int i=row; i<m-1-row; i++) {
					result[i][n-column-1] = count;
					count++;
				}
				direction++;
				break;
			case 2:
				for(int j=n-column-1; j>column; j--) {
					result[m-1-row][j] = count;
					count++;
				}
				direction++;
				break;
			case 3:
				for(int i=m-1-row; i>row; i--) {
					result[i][column] = count;
					count++;
				}
				direction = 0;
				column++;
				row++;
				break;
			}	
		}
		
		printResult(result, m, n);
	}
}

4. 메모

  • 배열을 예쁘게 출력하는 방법
    →  "%3d" 처럼 배열의 모든 원소들에게 사이즈를 할당함으로서 배열의 형태를 정사각형 형태로 출력할 수 있다.

'Algorithm > 알고리즘 문제 풀이' 카테고리의 다른 글

알고리즘 (6월 15일)  (0) 2022.06.15
알고리즘 (6월 13일) - (3)  (0) 2022.06.13
알고리즘 (6월 13일)  (0) 2022.06.13
알고리즘 (6월 12일)  (0) 2022.06.12
알고리즘 (6월 10일)  (0) 2022.06.11