문제
https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV5PobmqAPoDFAUq
풀이
import java.util.Scanner;
class Algorithm220207 {
public static void snail(int n) {
int[][] arr = new int[n][n];
int[] dr = { 0, 1, 0, -1 }; // 행 변화값 (우 하 좌 상)
int[] dc = { 1, 0, -1, 0 }; // 열 변화값 (우 하 좌 상)
int[] dd = { 0, 1, 2, 3 }; // 인덱스 값
int row = 0; // 행 초기화
int column = 0; // 열 초기화
int cnt = 0; // dd의 인덱스 초기화
// 배열 채우기
for (int i = 1; i <= n * n; i++) {
int dRow = row + dr[dd[cnt]]; // 다음번 움직일 행
int dColumn = column + dc[dd[cnt]]; // 다음번 움직일 열
// 방향을 바꿔 줄 조건
if (dRow < 0 || dRow >= n || dColumn < 0 || dColumn >= n || arr[dRow][dColumn] != 0) {
cnt = (cnt + 1) % 4; // cnt가 3을 넘어가지 않게 해줌
dRow = row + dr[dd[cnt]];
dColumn = column + dc[dd[cnt]];
}
arr[row][column] = i;
row = dRow;
column = dColumn;
}
for (int i=0; i<n; i++) {
for (int j=0; j<n; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int testNum = kb.nextInt(); // 테스트 케이스의 개수
for (int i = 1; i <= testNum; i++) {
int snailNum = kb.nextInt(); // 각 테스트 케이스
System.out.println("#" + i);
snail(snailNum);
}
}
}
참고
https://www.youtube.com/watch?v=8tjHHJEWkbA&t=2s
'💻 Computer Science > 알고리즘' 카테고리의 다른 글
재귀함수 (Recursive Function) (0) | 2023.07.06 |
---|---|
[프로그래머스] 없는 숫자 더하기 (Java) (0) | 2022.08.27 |
DFS (깊이 우선 탐색) (0) | 2022.05.13 |
LRU (Least Recently Used) (0) | 2022.05.04 |
투 포인터 (two pointers) (0) | 2022.04.21 |
[프로그래머스] n^2 배열 자르기 (Java) (0) | 2022.04.18 |