深度搜索找联通块

This commit is contained in:
LittleSheep 2024-05-01 15:56:43 +08:00
parent 63e337e067
commit 7650e8edfb

46
walking-in-maze/main.cc Normal file
View File

@ -0,0 +1,46 @@
#include <iostream>
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;
}