SW Expert Academy
SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!
swexpertacademy.com
풀이 과정
NxN 차원 배열에 시계방향으로 바깥쪽부터 안쪽까지 숫자를 1씩 늘려가면서 채우는 문제이다.
배열에 채워야 할 수가 NxN으로 정해져 있으므로 이미 채워진 블록, 배열의 끝을 만나면 방향을 진행 방향의 오른쪽으로 바꿔가며 배열에 수를 N^2번 채우면 된다.
처음 풀 때 while문을 이용해서 좀 지저분하게 짰는데 그 코드도 맨 아래에 남겨놓았다.
소스 코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
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[] dy = {0, 1, 0, -1};
int[] dx = {1, 0, -1, 0};
for (int tc = 1; tc <= T; tc++) {
int N = Integer.parseInt(br.readLine());
int[][] board = new int[N][N];
int y = 0; int x = 0;
int num = 1;
int direction = 0;
for (int i = 0; i < N*N; i++) {
board[y][x] = num++;
int ny = y + dy[direction];
int nx = x + dx[direction];
if (ny < 0 || ny > N-1 || nx < 0 || nx > N-1 || board[ny][nx] != 0) {
direction++;
if (direction == 4) {
direction = 0;
}
}
y += dy[direction];
x += dx[direction];
}
System.out.printf("#%d\n", tc);
for (int i = 0; i < N; i++) {
for (int j : board[i]) {
System.out.print(j+" ");
}
System.out.println();
}
}
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
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());
for (int tc = 1; tc <= T; tc++) {
int N = Integer.parseInt(br.readLine());
int[][] board = new int[N][N];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
board[i][j] = 0;
}
}
int direction = 0;
int r = 0; int c = 0;
int num = 1;
while (board[r][c] == 0) {
board[r][c] = num++;
if (direction == 0 ) {
if (c+1 < N && board[r][c+1] == 0) {
c++;
} else {
if (r+1 < N && board[r+1][c] == 0) {
direction++;
} else {
break;
}
}
}
if (direction == 1) {
if (r+1 < N && board[r+1][c] == 0) {
r++;
} else {
if (c-1 >= 0 && board[r][c-1] == 0) {
direction++;
} else {
break;
}
}
}
if (direction == 2) {
if (c-1 >= 0 && board[r][c-1] == 0) {
c--;
} else {
if (r-1 >= 0 && board[r-1][c] == 0) {
direction++;
} else {
break;
}
}
}
if (direction == 3) {
if (r-1 >= 0 && board[r-1][c] == 0) {
r--;
} else {
if (c+1 < N && board[r][c+1] == 0) {
direction = 0;
c++;
} else {
break;
}
}
}
}
System.out.printf("#%d\n", tc);
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
}
}
'알고리즘 문제 풀이 > 삼성 Swea' 카테고리의 다른 글
SWEA 2115 - [모의 SW 역량테스트] 벌꿀채취 [파이썬] (0) | 2023.03.04 |
---|---|
SWEA 1231 - 중위 순회 [파이썬] (0) | 2023.02.11 |
SWEA 10726. 이진수 표현 [Java] (0) | 2023.02.04 |
SWEA 1288. 새로운 불면증 치료법 [Java] (0) | 2023.02.04 |
SWEA - 1206. View (0) | 2022.07.24 |