문제출처 - SW Expert Academy
https://swexpertacademy.com/main/code/problem/problemDetail.do
SW Expert Academy
SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!
swexpertacademy.com
[제약사항]
달팽이의 크기 N은 1 이상 10 이하의 정수이다. (1 ≤ N ≤ 10)
[입력]
가장 첫 줄에는 테스트 케이스의 개수 T가 주어지고, 그 아래로 각 테스트 케이스가 주어진다.
각 테스트 케이스에는 N이 주어진다.
[출력]
각 줄은 '#t'로 시작하고, 다음 줄부터 빈칸을 사이에 두고 달팽이 숫자를 출력한다.
(t는 테스트 케이스의 번호를 의미하며 1부터 시작한다.)
달팽이 문제풀이
import java.util.Scanner;
import java.io.FileInputStream;
class Solution
{
public static int num=1;
public static void main(String args[]) throws Exception
{
Scanner sc = new Scanner(System.in);
int T;
T=sc.nextInt();
for(int testCase=1;testCase<=T;testCase++){
num=1;
int N=sc.nextInt();
int right=0; //오른쪽으로 갈 때의 행
int bottom=N-1; //아래로 내려갈때의 열
int left=N-1; //왼쪽 운행에서 행
int top=0; //위쪽 운행에서 열
int arr[][]=new int[N][N];
while(num<(N*N)+1){
//우방
for(int j=top;j<=bottom;j++) {
arr[right][j]=num++;
}
right++;
//아래방향
for(int i=right;i<=left;i++ ) {
arr[i][bottom]=num++;
}
bottom--;
//왼쪽방향
for(int j=bottom;j>=top;j--) {
arr[left][j]=num++;
}
left--;
//위쪽방향
for(int i=left;i>=right;i--) {
arr[i][top]=num++;
}
top++;
}
System.out.println("#"+testCase);
for(int a[]:arr){
for(int k:a){
System.out.printf("%2d ",k);
}
System.out.println();
}
}
}
}
달팽이 문제풀기 - 재귀함수 사용
'노력만이 살길! > 알고리즘' 카테고리의 다른 글
순열, 조합, 중복순열, 중복조합 구현하기 (0) | 2022.02.07 |
---|---|
[Java] 1954번 달팽이 - 재귀함수 사용 (SW Expert Academy ) (0) | 2022.02.07 |
2001 파리 퇴치 (SW Expert Academy ) (0) | 2022.02.05 |
합병정렬(Merge Sort) (0) | 2019.07.24 |
시간복잡도의 점근적 표기법 (2) | 2019.07.24 |