본문 바로가기
알고리즘/기타 알고리즘

[알고리즘] 달팽이 배열로 숫자 채우기

by lanuarius19 2022. 4. 25.
728x90

코드

 

public class Study1 {
	public static void main(String[] args) {
		
		int[][] array = new int[5][5];
		int num = 0;
		int numberCount = 5;
		int sw = 1;
		
		int i = 0;
		int j = -1;
		
		while(true) {
			
			for(int x=0; x<numberCount; x++) {
				num ++;
				j += sw;
				array[i][j] = num;
			}
			
			numberCount--;
			
			if(numberCount == 0) {
				break;
			}
			
			for(int x=0; x<numberCount; x++) {
				num ++;
				i += sw;
				array[i][j] = num;
			}
			
			sw *= (-1);
		}
		
		for(int r=0; r<array.length; r++) {
			for(int c=0; c<array[r].length; c++) {
				System.out.print(array[r][c] + "\t");
			}
			System.out.println();
		}
	}
}

 

 

결과

 

1
2
3
4
5
16
17
18
19
6
15
24
25
20
7
14
23
22
21
8
13
12
11
10
9
728x90

댓글