SW Expert Academy
SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!
www.swexpertacademy.com
방향 전환 문제 연습하기 좋은 문제 같다.
풀이
- 먼저 N이 1일 때는 2차원 배열을 만들지 못하므로 바로 1을 출력하도록 처리해주었다.
- 우 -> 하 -> 좌 -> 상 순서로 계속 움직일 것이므로 미리 순서에 맞게 dx, dy 배열을 저장.
- 처음 좌표는 (0,0) 방향은 dir=0 (우 방향)
- i부터 N*N까지 순차적으로 저장해준다.
- 범위를 벗어나거나 이동할 곳에 값이 이미 있는 경우마다 방향을 회전해준다.
- 좌표를 다시 원래대로 돌려준 후에
- 방향 전환하고
- 다시 전환한 방향으로 이동
import java.io.*;
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
int dx[] = {0,1,0,-1};
int dy[] = {1,0,-1,0};
for(int tc=1; tc<=T; tc++) {
int N = Integer.parseInt(br.readLine());
//N 이 1인 경우를 따로 처리
if(N == 1) {
System.out.println("#"+tc);
System.out.println(1);
continue;
}
int[][] arr = new int[N][N];
int x = 0;
int y = 0;
int dir = 0; //처음 방향은 0(우 방향)
for(int i=0; i<N*N; i++) {
arr[x][y] = i+1;
x += dx[dir];
y += dy[dir];
//범위를 벗어나는 경우 방향 전환
if(x >= N || y >= N || x < 0 || y < 0) {
//원래 위치로 돌려주고
x -= dx[dir];
y -= dy[dir];
//방향 전환 (0->1 우에서 하/ 1->2 하에서 좌/ 2->3 좌에서 상/ 3->0 상에서 우)
dir = (dir+1)%4;
//전환한 방향으로 이동
x += dx[dir];
y += dy[dir];
}
//이동할 곳에 값이 있는 경우 방향 전환
if(arr[x][y] != 0) {
x -= dx[dir];
y -= dy[dir];
dir = (dir+1)%4;
x += dx[dir];
y += dy[dir];
}
}
System.out.println("#"+tc);
for(int i=0; i<N; i++) {
for(int j=0; j<N; j++) {
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}
}
'SWEA > D2' 카테고리의 다른 글
| [SWEA] 1946. 간단한 압축 풀기 (0) | 2019.05.14 |
|---|---|
| [SWEA] 1948. 날짜 계산기 (0) | 2019.05.14 |
| [SWEA] 1959. 두 개의 숫자열 (0) | 2019.05.14 |
| [SWEA] 1961. 숫자 배열 회전 (0) | 2019.05.14 |
| [SWEA] 1974. 스도쿠 검증 (0) | 2019.05.03 |