diff --git a/cpp/2305/LC230509.cpp b/cpp/2305/LC230509.cpp new file mode 100644 index 0000000..36d45d8 --- /dev/null +++ b/cpp/2305/LC230509.cpp @@ -0,0 +1,41 @@ +#include +#include + +/** + * 54. Spiral Matrix + * + * Given an m x n matrix, return all elements of the matrix in spiral order. + */ + +class LC230509 { +private: + static inline constexpr int dX[] = {0, 1, 0, -1}; + static inline constexpr int dY[] = {1, 0, -1, 0}; + +public: + static std::vector spiralOrder(const std::vector>&) noexcept; +}; + +template +constexpr bool is_valid(T x, T y, T m, T n) { + return (x >= 0) && (x < m) && (y >= 0) && (y < n); +} + +std::vector LC230509::spiralOrder(const std::vector>& G) noexcept { + const int m = G.size(), n = G.front().size(), k = m * n; + std::vector ret(k); + std::bitset<128> vis; + for (int pos = 0, x = 0, y = 0, d = 0;;) { + ret[pos] = G[x][y]; + if (++pos >= k) + break; + vis[x * n + y] = true; + if (!is_valid(x + dX[d], y + dY[d], m, n) || vis[(x + dX[d]) * n + (y + dY[d])]) + d = (d + 1) & 3; + x += dX[d]; + y += dY[d]; + } + return ret; +} + +using Solution = LC230509; diff --git a/cpp/2305/defs.h b/cpp/2305/defs.h index 3e048b2..efbebe4 100644 --- a/cpp/2305/defs.h +++ b/cpp/2305/defs.h @@ -99,4 +99,13 @@ public: static int countTime(const std::string&) noexcept; }; +class LC230509 { +private: + static inline constexpr int dX[] = {0, 1, 0, -1}; + static inline constexpr int dY[] = {1, 0, -1, 0}; + +public: + static std::vector spiralOrder(const std::vector>&) noexcept; +}; + #endif //LEETCODE_CPP_DEFS_H diff --git a/cpp/2305/main.cpp b/cpp/2305/main.cpp index dec0240..a041976 100644 --- a/cpp/2305/main.cpp +++ b/cpp/2305/main.cpp @@ -12,13 +12,11 @@ std::ostream& operator<<(std::ostream& os, const std::vector& x) noexcept { } int main() { - std::cout << LC230508CN::minPushBox( - {{'#','.','.','#','#','#','#','#'}, - {'#','.','.','T','#','.','.','#'}, - {'#','.','.','.','#','B','.','#'}, - {'#','.','.','.','.','.','.','#'}, - {'#','.','.','.','#','.','S','#'}, - {'#','.','.','#','#','#','#','#'}} - ); + std::cout << LC230509::spiralOrder({ + {2,3,4}, + {5,6,7}, + {8,9,10}, + {11,12,13} + }); return 0; }