From 7650e8edfb70428564028a8a92a88360734d7a06 Mon Sep 17 00:00:00 2001 From: LittleSheep Date: Wed, 1 May 2024 15:56:43 +0800 Subject: [PATCH] =?UTF-8?q?:white=5Fcheck=5Fmark:=20=E6=B7=B1=E5=BA=A6?= =?UTF-8?q?=E6=90=9C=E7=B4=A2=E6=89=BE=E8=81=94=E9=80=9A=E5=9D=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- walking-in-maze/main.cc | 46 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 walking-in-maze/main.cc diff --git a/walking-in-maze/main.cc b/walking-in-maze/main.cc new file mode 100644 index 0000000..0bf38f1 --- /dev/null +++ b/walking-in-maze/main.cc @@ -0,0 +1,46 @@ +#include +using namespace std; +#define MAXN 55 + +int maze[MAXN][MAXN]; +bool visited[MAXN][MAXN] = {false}; + +int sum = 0; + +int dx[4] = {0, 0, 1, -1}; +int dy[4] = {1, -1, 0, 0}; + +bool in_range(int x, int y, int rows, int cols) { + return x >= 0 && x < rows && y >= 0 && y < cols; +} + +void dfs(int x, int y, int rows, int cols) { + if (maze[x][y] == 2 || !in_range(x, y, rows, cols) || visited[x][y]) + return; + + visited[x][y] = true; + sum++; + + for (int i = 0; i < 4; i++) { + int px = x + dx[i]; + int py = y + dy[i]; + dfs(px, py, rows, cols); + } +} + +int main() { + int N, M; + cin >> N >> M; + int start_x, start_y; + for (int x = 0; x < N; x++) { + for (int y = 0; y < M; y++) { + cin >> maze[x][y]; + if (maze[x][y] == 6) { + start_x = x; + start_y = y; + } + } + } + dfs(start_x, start_y, N, M); + cout << sum << endl; +}