G - Спиралька

mail@pastecode.io avatar
unknown
c_cpp
a year ago
1.3 kB
18
Indexable
Never
#include <bits/stdc++.h>

using namespace std;

int a[11][11], n;

void fill(int i, int j, int k, int dir, int first, int last) {
    if (k > n * n) {
        return;
    }
    
    a[i][j] = k;
    
    // to right
    if (dir == 0) {
        if (j < last) {
            fill(i, j + 1, k + 1, dir, first, last);
        } else {
            fill(i + 1, j, k + 1, 1, first, last);
        }
    } else if (dir == 1) {
        if (i < last) {
            fill(i + 1, j, k + 1, dir, first, last);
        } else {
            fill(i, j - 1, k + 1, 2, first, last);
        }
    } else if (dir == 2) {
        if (j > first) {
            fill(i, j - 1, k + 1, dir, first, last);
        } else {
            fill(i - 1, j, k + 1, 3, first, last);
        }
    } else {
        if (i > first + 1) {
            fill(i - 1, j, k + 1, dir, first, last);
        } else {
            fill(i, j + 1, k + 1, 0, first + 1, last - 1);
        }
    }
}


int main() {
    cin >> n;
    fill(1, 1, 1, 0, 1, n);
    
    for (int i = 1; i <= n; ++i) {
        for (int j = 1; j <= n; ++j) {
            cout << a[i][j] << ' ';
        }
        cout << endl;
    }
    
    return 0; 
}

/*
1   2   3   4   5
16  17  18  19  6
15  24  25  20  7
14  23  22  21  8
13  12  11  10  9

*/