Notice
Recent Posts
Link
- Today
- Total
hye-log
[SWEA]1954번 달팽이 숫자(JAVA) 본문
0. 문제 링크
https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV5PobmqAPoDFAUq
1. 문제 설명
1) N*N 크기에 오른쪽 -> 아래 -> 왼쪽 -> 위 순으로 숫자 출력하기
2. 입출력
// input
2 // 테스트 케이스의 개수
3
4
// output
#1
1 2 3
8 9 4
7 6 5
#2
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
3. 코드
import java.util.*;
public class swea1954 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for(int t = 1; t <= T; t++) {
int N = sc.nextInt();
int[][] arr = new int[N][N];
int k = N;
int r = 0; // 세로
int c = -1; // 가로
int num = 1; // 배열의 값
while(k > 0) {
for(int i = 0; i < k; i++) {
arr[r][++c] = num++; // 가로 증가
}
k--; // 방향 바뀌면서 감소
for(int i = 0; i < k; i++) {
arr[++r][c] = num++; // 세로 증가
}
for(int i = 0; i < k; i++) {
arr[r][--c] = num++; // 가로 감소
}
k--; // 방향 바뀌면서 감소
for(int i = 0; i < k; i++) {
arr[--r][c] = num++; // 세로 감소
}
}
// 출력
System.out.println("#"+t);
for(int i = 0; i < N; i++) {
for(int j = 0; j < N; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
}
실행 결과
4. 회고
1) 방향을 바꾸면서 작성하는 숫자의 개수가 달라짐을 이용하여 반복문으로 해결
5. Github
https://github.com/iihye/Algorithm/blob/main/SWEA/swea1954.java
728x90
'CodingTest > SWEA' 카테고리의 다른 글
[SWEA]6808번 규영이와 인영이의 카드게임(JAVA) (0) | 2023.08.06 |
---|---|
[SWEA]2001번 파리 퇴치(JAVA) (0) | 2023.08.06 |
[SWEA]5215번 햄버거 다이어트(JAVA) (0) | 2023.08.06 |
[SWEA]1210번 Ladder1(JAVA) (0) | 2023.08.06 |
[SWEA]6958번 동철이의 프로그래밍 대회(JAVA) (0) | 2023.07.30 |
Comments