From 4bfff21cdf21b9fbb5f3afea40ded2334e7558f1 Mon Sep 17 00:00:00 2001 From: Eatswap Date: Fri, 7 Apr 2023 08:49:39 +0800 Subject: [PATCH] add: 230407 --- cpp/2304/230407.cpp | 58 +++++++++++++++++++++++++++++++++++++++++ cpp/2304/CMakeLists.txt | 2 +- 2 files changed, 59 insertions(+), 1 deletion(-) create mode 100644 cpp/2304/230407.cpp diff --git a/cpp/2304/230407.cpp b/cpp/2304/230407.cpp new file mode 100644 index 0000000..8ac8e0d --- /dev/null +++ b/cpp/2304/230407.cpp @@ -0,0 +1,58 @@ +#include +#include +#include +#include +#include + +/** + * 1020. Number of Enclaves + * + * You are given an m x n binary matrix grid, where 0 represents a sea cell and 1 represents a land cell. + * A move consists of walking from one land cell to another adjacent (4-directionally) land cell or walking off the boundary of the grid. + * Return the number of land cells in grid for which we cannot walk off the boundary of the grid in any number of moves. + */ + +class Solution { +private: + static const inline int dX[] = {0, 1, 0, -1}, dY[] = {1, 0, -1, 0}; +public: + static int numEnclaves(std::vector>&); +}; + +int Solution::numEnclaves(std::vector>& G) { + const int m = G.size(), n = G.front().size(); + auto setAs0 = [&](int x, int y) { + if (G[x][y] == 0) return 0; + std::queue> q; + q.emplace(x, y); + int ret = 0; + std::vector vis(m * n); + for (int nx, ny; !q.empty(); q.pop()) { + auto&& [cx, cy] = q.front(); + G[cx][cy] = 0; + ++ret; + for (int i = 0; i < 4; ++i) { + nx = cx + dX[i]; + ny = cy + dY[i]; + if (nx >= 0 && nx < m && ny >= 0 && ny < n && G[nx][ny] != 0 && !vis[nx * n + ny]) { + q.emplace(nx, ny); + vis[nx * n + ny] = true; + } + } + } + return ret; + }; + for (int i = 0; i < n; ++i) + setAs0(0, i), setAs0(m - 1, i); + for (int i = 1; i < m - 1; ++i) + setAs0(i, 0), setAs0(i, n - 1); + return std::transform_reduce(G.begin(), G.end(), 0, [](int x, int y){ return x + y; }, [](auto&& x) { + return std::reduce(x.begin(), x.end(), 0); + }); +} + +int main() { + std::vector> a {{0,0,0,0},{1,0,1,0},{0,1,1,0},{0,0,0,0}}; + std::cout << Solution::numEnclaves(a); + return 0; +} diff --git a/cpp/2304/CMakeLists.txt b/cpp/2304/CMakeLists.txt index 3d86cfd..97b398f 100644 --- a/cpp/2304/CMakeLists.txt +++ b/cpp/2304/CMakeLists.txt @@ -4,4 +4,4 @@ PROJECT(2304) SET(CMAKE_CXX_STANDARD 23) SET(CMAKE_EXPORT_COMPILE_COMMANDS true) -ADD_EXECUTABLE(2304 230406.cpp) +ADD_EXECUTABLE(2304 230407.cpp)