Skip to content

Commit

Permalink
Added Set Matrix Zeroes
Browse files Browse the repository at this point in the history
  • Loading branch information
Ace-Krypton committed Sep 22, 2023
1 parent f3fcdad commit 3c61b7d
Show file tree
Hide file tree
Showing 3 changed files with 80 additions and 0 deletions.
11 changes: 11 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -854,4 +854,15 @@ add_executable(SpiralMatrix
target_link_libraries(
SpiralMatrix
GTest::gtest_main
)

# Set Matrix Zeroes
add_executable(SetMatrixZeroes
Medium/SetMatrixZeroes/include/solution.hpp
Medium/SetMatrixZeroes/tests/test.cpp
)

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

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

class Solution {
public:
static auto set_zeroes(std::vector<std::vector<int32_t>> &matrix) -> void {
const int32_t row_length = matrix.size();
const int32_t column_length = matrix[0].size();

std::vector<bool> row_zero(row_length);
std::vector<bool> column_zero(column_length);

for (size_t row = 0; row < row_length; ++row) {
for (size_t column = 0; column < column_length; ++column) {
if (matrix[row][column] == 0) {
row_zero[row] = true;
column_zero[column] = true;
}
}
}

for (size_t row = 0; row < row_length; ++row) {
for (size_t column = 0; column < column_length; ++column) {
if (row_zero[row] || column_zero[column]) {
matrix[row][column] = 0;
}
}
}
}
};
35 changes: 35 additions & 0 deletions Medium/SetMatrixZeroes/tests/test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#include "../include/solution.hpp"

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

TEST_F(SetMatrixZeroes, FirstTest) {
std::vector<std::vector<int32_t>> matrix =
{{1, 1, 1}, {1, 0, 1}, {1, 1, 1}};

Solution::set_zeroes(matrix);

std::vector<std::vector<int32_t>> expected =
{{1, 0, 1}, {0, 0, 0}, {1, 0, 1}};

ASSERT_EQ(matrix, expected);
}

TEST_F(SetMatrixZeroes, SecondTest) {
std::vector<std::vector<int32_t>> matrix =
{{0, 1, 2, 0}, {3, 4, 5, 2}, {1, 3, 1, 5}};

Solution::set_zeroes(matrix);

std::vector<std::vector<int32_t>> expected =
{{0, 0, 0, 0}, {0, 4, 5, 0}, {0, 3, 1, 0}};

ASSERT_EQ(matrix, expected);
}

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

0 comments on commit 3c61b7d

Please sign in to comment.