1
0
Fork 0
mirror of https://gitlab.com/mfocko/CodeWars.git synced 2024-09-18 21:56:57 +02:00
CodeWars/5kyu/the_clockwise_spiral/solution.cpp
Matej Focko fc899b0b02
chore: initial commit
Signed-off-by: Matej Focko <mfocko@redhat.com>
2021-12-28 16:19:58 +01:00

32 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;
}