暴力深度优先搜索解决翻卡片

This commit is contained in:
LittleSheep 2024-05-19 15:58:59 +08:00
parent 710ee8853c
commit 4e3b93b7c2

69
flip-card/main.cc Normal file
View File

@ -0,0 +1,69 @@
#include <algorithm>
#include <cstring>
#include <iostream>
using namespace std;
const int N = 50;
char tiles[N + 5][N + 5];
bool visited[N + 5][N + 5];
int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, -1, 1};
bool in_range(int x, int y, int rows, int cols) {
return x >= 0 && x < rows && y >= 0 && y < cols;
}
int dfs(int x, int y, int rows, int cols) {
if (!in_range(x, y, rows, cols) || visited[x][y] || tiles[x][y] == 'B') {
return 0;
}
visited[x][y] = true;
int size = 1;
for (int i = 0; i < 4; ++i) {
int px = x + dx[i];
int py = y + dy[i];
size += dfs(px, py, rows, cols);
}
return size;
}
int find_largest_area(int rows, int cols) {
int max_size = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (!visited[i][j] && tiles[i][j] == 'A') {
int size = dfs(i, j, rows, cols);
max_size = max(max_size, size);
}
}
}
return max_size;
}
int main() {
int n;
cin >> n;
for (int x = 0; x < n; x++)
for (int y = 0; y < n; y++)
cin >> tiles[x][y];
int max_chunk = 0;
for (int x = 0; x < n; x++) {
for (int y = 0; y < n; y++) {
if (tiles[x][y] == 'A')
continue;
tiles[x][y] = 'A';
memset(visited, 0, sizeof visited);
max_chunk = max(max_chunk, find_largest_area(n, n));
tiles[x][y] = 'B';
}
}
cout << max_chunk << endl;
}