mirror of
https://gitlab.com/mfocko/CodeWars.git
synced 2024-11-25 02:01:56 +01:00
33 lines
634 B
C++
33 lines
634 B
C++
|
#include <vector>
|
||
|
|
||
|
static void next_diff(int &dy, int &dx) {
|
||
|
int new_dx = -dy, new_dy = dx;
|
||
|
dy = new_dy;
|
||
|
dx = new_dx;
|
||
|
}
|
||
|
|
||
|
std::vector<std::vector<int>> create_spiral(int n) {
|
||
|
if (n < 1) {
|
||
|
return {};
|
||
|
}
|
||
|
|
||
|
auto result = std::vector<std::vector<int>>(
|
||
|
static_cast<size_t>(n), std::vector<int>( static_cast<size_t>(n), 0 )
|
||
|
);
|
||
|
|
||
|
int y = 0, x = 0;
|
||
|
int dy = 0, dx = 1;
|
||
|
for (int i = 1, max = n * n; i <= max; i++) {
|
||
|
result[y][x] = i;
|
||
|
|
||
|
if (y + dy == n || y + dy < 0 || x + dx == n || x + dx < 0 || result[y + dy][x + dx] != 0) {
|
||
|
next_diff(dy, dx);
|
||
|
}
|
||
|
|
||
|
y += dy;
|
||
|
x += dx;
|
||
|
}
|
||
|
|
||
|
return result;
|
||
|
}
|