From 9c430083df97332e05820b54044729561aeca4a7 Mon Sep 17 00:00:00 2001 From: Eat-Swap Date: Tue, 14 Jun 2022 20:12:28 +0800 Subject: [PATCH] add: 220614-CN --- cpp/2206/220614-CN.cpp | 31 +++++++++++++++++++++++++++++++ cpp/2206/CMakeLists.txt | 2 +- 2 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 cpp/2206/220614-CN.cpp diff --git a/cpp/2206/220614-CN.cpp b/cpp/2206/220614-CN.cpp new file mode 100644 index 0000000..a763f16 --- /dev/null +++ b/cpp/2206/220614-CN.cpp @@ -0,0 +1,31 @@ +#include +#include + +/** + * 498. Diagonal Traverse + * Given an m x n matrix mat, return an array of all the elements of the array in a diagonal order. + */ + +class Solution { +public: + static std::vector findDiagonalOrder(const std::vector>& mat) { + const int m = mat.size(), n = mat.front().size(); + std::vector ans; + ans.reserve(m * n); + for (int i = 0; i < m + n; ++i) + // if (i & 1) -> from x min to x max (m) + // else -> from y min to y max (n) + if (!(i & 1)) + for (int x = std::min(i, m - 1), y = std::min(n, i - x); y < n && x >= 0; --x, ++y) + ans.push_back(mat[x][y]); + else + for (int y = std::min(i, n - 1), x = std::min(m, i - y); x < m && y >= 0; ++x, --y) + ans.push_back(mat[x][y]); + return ans; + } +}; + +int main() { + auto ret = Solution::findDiagonalOrder({{1,2,3},{4,5,6},{7,8,9},{10,11,12}}); + return 0; +} diff --git a/cpp/2206/CMakeLists.txt b/cpp/2206/CMakeLists.txt index 5947ba9..c7fb8a6 100644 --- a/cpp/2206/CMakeLists.txt +++ b/cpp/2206/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2206) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2206 220607.cpp) +ADD_EXECUTABLE(2206 220614-CN.cpp)