Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions cpp/exercises/practice/spiral-matrix/spiral_matrix.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,43 @@

namespace spiral_matrix {

std::vector<std::vector<uint32_t>> spiral_matrix(uint32_t size) {
std::vector<std::vector<uint32_t>> matrix(size, std::vector<uint32_t>(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
7 changes: 5 additions & 2 deletions cpp/exercises/practice/spiral-matrix/spiral_matrix.h
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
#if !defined(SPIRAL_MATRIX_H)
#ifndef SPIRAL_MATRIX_H
#define SPIRAL_MATRIX_H

namespace spiral_matrix {
#include <vector>
#include <cstdint>

namespace spiral_matrix {
std::vector<std::vector<uint32_t>> spiral_matrix(uint32_t size);
} // namespace spiral_matrix

#endif // SPIRAL_MATRIX_H