mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-10 00:09:06 +01:00
problems(cpp): add “1572. Matrix Diagonal Sum”
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
0965799a48
commit
e5c5a79e70
1 changed files with 46 additions and 0 deletions
46
problems/matrix-diagonal-sum.cpp
Normal file
46
problems/matrix-diagonal-sum.cpp
Normal file
|
@ -0,0 +1,46 @@
|
|||
#include <cassert>
|
||||
#include <vector>
|
||||
|
||||
class Solution {
|
||||
struct indices {
|
||||
int x;
|
||||
int y;
|
||||
|
||||
bool operator==(const indices& other) const = default;
|
||||
indices& operator+=(const indices& other) {
|
||||
x += other.x;
|
||||
y += other.y;
|
||||
return *this;
|
||||
}
|
||||
|
||||
int operator[](const std::vector<std::vector<int>>& mat) const {
|
||||
return mat[y][x];
|
||||
}
|
||||
};
|
||||
|
||||
public:
|
||||
int diagonalSum(const std::vector<std::vector<int>>& mat) {
|
||||
int sum = 0;
|
||||
|
||||
indices down{0, 0}, up{0, static_cast<int>(mat.size()) - 1};
|
||||
indices d_down{1, 1}, d_up{1, -1};
|
||||
for (std::size_t i = 0; i < mat.size(); ++i, down += d_down, up += d_up) {
|
||||
sum += down[mat];
|
||||
if (down != up) {
|
||||
sum += up[mat];
|
||||
}
|
||||
}
|
||||
|
||||
return sum;
|
||||
}
|
||||
};
|
||||
|
||||
int main() {
|
||||
Solution s;
|
||||
|
||||
assert((s.diagonalSum({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}) == 25));
|
||||
assert((s.diagonalSum(
|
||||
{{1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}}) == 8));
|
||||
assert((s.diagonalSum({{5}}) == 5));
|
||||
return 0;
|
||||
}
|
Loading…
Reference in a new issue