문제
내가 작성한 정답
class Solution {
public int[][] solution(int n) {
int[][] answer = new int[n][n];
int num = 1; // 채워 넣을 숫자
int top = 0; // 현재 위쪽 경계
int bottom = n - 1; // 현재 아래쪽 경계
int left = 0; // 현재 왼쪽 경계
int right = n - 1; // 현재 오른쪽 경계
while (top <= bottom && left <= right) {
// 1. 왼→오 (위쪽 행)
for (int c = left; c <= right; c++) {
answer[top][c] = num++;
}
top++; // 위쪽 경계 한 칸 내려감
// 2. 위→아래 (오른쪽 열)
for (int r = top; r <= bottom; r++) {
answer[r][right] = num++;
}
right--; // 오른쪽 경계 한 칸 왼쪽으로
// 3. 오→왼 (아래쪽 행)
if (top <= bottom) {
for (int c = right; c >= left; c--) {
answer[bottom][c] = num++;
}
bottom--; // 아래쪽 경계 한 칸 위로
}
// 4. 아래→위 (왼쪽 열)
if (left <= right) {
for (int r = bottom; r >= top; r--) {
answer[r][left] = num++;
}
left++; // 왼쪽 경계 한 칸 오른쪽으로
}
}
return answer;
}
}다른 사람들의 정답
class Solution {
public int[][] solution(int n) {
int[][] answer = new int[n][n];
int num = 1;
int x = 0, y = 0;
int dx[] = {0, 1, 0, -1};
int dy[] = {1, 0, -1, 0};
int direction = 0;
while (num <= n * n) {
answer[x][y] = num++;
int nx = x + dx[direction];
int ny = y + dy[direction];
if (nx < 0 || nx >= n || ny < 0 || ny >= n || answer[nx][ny] != 0) {
direction = (direction + 1) % 4; //범위 밖에 나갔을 때 방향전환
nx = x + dx[direction];
ny = y + dy[direction];
}
x = nx;
y = ny;
}
return answer;
}
}
class Solution {
public int[][] solution(int n) {
int[][] answer = new int[n][n];
int num=1;
int start=0;
int end=n;
while(num <= n*n){
//->
for(int j=start;j<end;j++)
answer[start][j]=num++;
//v
for(int i=start+1;i<end;i++)
answer[i][end-1]=num++;
//<
for(int j=end-2;j>=start;j--)
answer[end-1][j]=num++;
//^
for(int i=end-2;i>start;i--)
answer[i][start]=num++;
start++;
end--;
}
return answer;
}
}Share article