## implementation

``````#include <cstdio>
#include <vector>
#include <algorithm>
#include <functional>
#define repeat_from(i,m,n) for (int i = (m); (i) < (n); ++(i))
using namespace std;
template <typename T, typename X> auto vectors(T a, X x) { return vector<T>(x, a); }
template <typename T, typename X, typename Y, typename... Zs> auto vectors(T a, X x, Y y, Zs... zs) { auto cont = vectors(a, y, zs...); return vector<decltype(cont)>(x, cont); }
const int dy[] = { 0, 1, 0, -1 };
const int dx[] = { 1, 0, -1, 0 };
int main() {
int n; scanf("%d", &n);
vector<vector<int> > f = vectors(0, n+2, n+2);
repeat_from (i,1,n+1) {
f[i][  0] = -1;
f[i][n+1] = -1;
f[  0][i] = -1;
f[n+1][i] = -1;
}
function<void (int, int, int, int)> dfs = [&](int y, int x, int i, int j) {
f[y][x] = i;
if (i == n*n) return;
int ny = y + dy[j];
int nx = x + dx[j];
if (f[ny][nx]) {
dfs(y, x, i, (j+1)%4);
} else {
dfs(ny, nx, i+1, j);
}
};
dfs(1, 1, 1, 0);
repeat_from (y,1,n+1) {
repeat_from (x,1,n+1) {
printf("%03d ", f[y][x]);
}
printf("\n");
}
return 0;
}
``````