Skip to content

Commit

Permalink
Added Spiral Matrix
Browse files Browse the repository at this point in the history
  • Loading branch information
Ace-Krypton committed Sep 21, 2023
1 parent a9094b9 commit 03f4bf8
Show file tree
Hide file tree
Showing 3 changed files with 90 additions and 0 deletions.
11 changes: 11 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -843,4 +843,15 @@ add_executable(RotateImage
target_link_libraries(
RotateImage
GTest::gtest_main
)

# Spiral Matrix
add_executable(SpiralMatrix
Medium/SpiralMatrix/include/solution.hpp
Medium/SpiralMatrix/tests/test.cpp
)

target_link_libraries(
SpiralMatrix
GTest::gtest_main
)
42 changes: 42 additions & 0 deletions Medium/SpiralMatrix/include/solution.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#pragma once

#include <vector>
#include <iostream>
#include <algorithm>
#include <gtest/gtest.h>

class Solution {
public:
static auto spiral_order(std::vector<std::vector<int32_t>> &matrix) -> std::vector<int32_t> {
std::vector<int32_t> result;
if (matrix.empty()) return result;

int32_t begin_row = 0;
auto end_row = static_cast<int32_t>(matrix.size() - 1);
int32_t begin_column = 0;
auto end_column = static_cast<int32_t>(matrix[0].size() - 1);

while (begin_row <= end_row && begin_column <= end_column) {
for (int32_t i = begin_column; i <= end_column; ++i) {
result.emplace_back(matrix[begin_row][i]);
} ++begin_row;
for (int32_t i = begin_row; i <= end_row; ++i) {
result.emplace_back(matrix[i][end_column]);
} --end_column;

if (begin_row <= end_row) {
for (int32_t i = end_column; i >= begin_column; --i) {
result.emplace_back(matrix[end_row][i]);
}
} --end_row;

if (begin_column <= end_column) {
for (int32_t i = end_row; i >= begin_row; --i) {
result.emplace_back(matrix[i][begin_column]);
}
} ++begin_column;
}

return result;
}
};
37 changes: 37 additions & 0 deletions Medium/SpiralMatrix/tests/test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
#include "../include/solution.hpp"

class SpiralMatrix : public ::testing::Test {
protected:
~SpiralMatrix() override = default;
};

TEST_F(SpiralMatrix, FirstTest) {
std::vector<std::vector<int32_t>> matrix =
{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

std::vector<int32_t> result =
Solution::spiral_order(matrix);

std::vector<int32_t> expected =
{1, 2, 3, 6, 9, 8, 7, 4, 5};

ASSERT_EQ(result, expected);
}

TEST_F(SpiralMatrix, SecondTest) {
std::vector<std::vector<int32_t>> matrix =
{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};

std::vector<int32_t> result =
Solution::spiral_order(matrix);

std::vector<int32_t> expected =
{1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7};

ASSERT_EQ(result, expected);
}

auto main(int argc, char **argv) -> int {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

0 comments on commit 03f4bf8

Please sign in to comment.