#include <iostream>
using namespace std;

int arr[1000][1000];

// 방향 설정: 오른쪽, 아래, 왼쪽, 위 (y가 행, x가 열)
int dy[4] = {0, 1, 0, -1};
int dx[4] = {1, 0, -1, 0};

int main() {
    int N;
    cin >> N;
    
    int y = 0, x = 0; // 시작 위치 (0, 0)
    int dir = 0;      // 처음 방향은 '오른쪽' (index 0)
    
    for (int num = 1; num <= N * N; num++) {
        arr[y][x] = num; // 현재 칸에 숫자 채우기
        
        // 다음에 이동할 칸 미리 계산해보기
        int ny = y + dy[dir];
        int nx = x + dx[dir];
        
        // 만약 다음 칸이 벽에 부딪히거나(범위 초과), 이미 숫자가 채워져 있다면?
        if (ny < 0 || ny >= N || nx < 0 || nx >= N || arr[ny][nx] != 0) {
            dir = (dir + 1) % 4; // 방향 꺾기 (우->하->좌->상->우...)
            // 꺾은 방향으로 다시 다음 칸 계산
            ny = y + dy[dir];
            nx = x + dx[dir];
        }
        
        // 실제로 이동하기
        y = ny;
        x = nx;
    }
    
    // 출력
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            cout << arr[i][j] << " ";
        }
        cout << "\n";
    }
    return 0;
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: