diff --git a/cpp/exercises/practice/spiral-matrix/spiral_matrix.cpp b/cpp/exercises/practice/spiral-matrix/spiral_matrix.cpp index 3428b39..603604b 100644 --- a/cpp/exercises/practice/spiral-matrix/spiral_matrix.cpp +++ b/cpp/exercises/practice/spiral-matrix/spiral_matrix.cpp @@ -2,4 +2,43 @@ namespace spiral_matrix { + std::vector> spiral_matrix(uint32_t size) { + std::vector> matrix(size, std::vector(size, 0)); + + if (size == 0) + return matrix; + + uint32_t num = 1; + int top = 0, bottom = size - 1; + int left = 0, right = size - 1; + + while (top <= bottom && left <= right) { + // move right + for (int col = left; col <= right; ++col) + matrix[top][col] = num++; + ++top; + + // move down + for (int row = top; row <= bottom; ++row) + matrix[row][right] = num++; + --right; + + // move left + if (top <= bottom) { + for (int col = right; col >= left; --col) + matrix[bottom][col] = num++; + --bottom; + } + + // move up + if (left <= right) { + for (int row = bottom; row >= top; --row) + matrix[row][left] = num++; + ++left; + } + } + + return matrix; + } + } // namespace spiral_matrix diff --git a/cpp/exercises/practice/spiral-matrix/spiral_matrix.h b/cpp/exercises/practice/spiral-matrix/spiral_matrix.h index cc56ad3..9c080f4 100644 --- a/cpp/exercises/practice/spiral-matrix/spiral_matrix.h +++ b/cpp/exercises/practice/spiral-matrix/spiral_matrix.h @@ -1,8 +1,11 @@ -#if !defined(SPIRAL_MATRIX_H) +#ifndef SPIRAL_MATRIX_H #define SPIRAL_MATRIX_H -namespace spiral_matrix { +#include +#include +namespace spiral_matrix { + std::vector> spiral_matrix(uint32_t size); } // namespace spiral_matrix #endif // SPIRAL_MATRIX_H