add: 230509

This commit is contained in:
Eatswap 2023-05-09 10:31:48 +08:00
parent 4dcff98da5
commit 2c85f9fc4b
Signed by: Eatswap
GPG Key ID: BE661106A1F3FA0B
3 changed files with 56 additions and 8 deletions

41
cpp/2305/LC230509.cpp Normal file
View File

@ -0,0 +1,41 @@
#include <vector>
#include <bitset>
/**
* 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<int> spiralOrder(const std::vector<std::vector<int>>&) noexcept;
};
template<typename T>
constexpr bool is_valid(T x, T y, T m, T n) {
return (x >= 0) && (x < m) && (y >= 0) && (y < n);
}
std::vector<int> LC230509::spiralOrder(const std::vector<std::vector<int>>& G) noexcept {
const int m = G.size(), n = G.front().size(), k = m * n;
std::vector<int> 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;

View File

@ -99,4 +99,13 @@ public:
static int countTime(const std::string&) noexcept; 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<int> spiralOrder(const std::vector<std::vector<int>>&) noexcept;
};
#endif //LEETCODE_CPP_DEFS_H #endif //LEETCODE_CPP_DEFS_H

View File

@ -12,13 +12,11 @@ std::ostream& operator<<(std::ostream& os, const std::vector<T>& x) noexcept {
} }
int main() { int main() {
std::cout << LC230508CN::minPushBox( std::cout << LC230509::spiralOrder({
{{'#','.','.','#','#','#','#','#'}, {2,3,4},
{'#','.','.','T','#','.','.','#'}, {5,6,7},
{'#','.','.','.','#','B','.','#'}, {8,9,10},
{'#','.','.','.','.','.','.','#'}, {11,12,13}
{'#','.','.','.','#','.','S','#'}, });
{'#','.','.','#','#','#','#','#'}}
);
return 0; return 0;
} }