題目會給予一張地圖,地圖中只有兩種字一種代表陸地,一種代表水,並再給予我們現在的座標(陸地),我們要找出除了現在所在的陸地之外,最大的陸地的大小(0與n-1是接在一起的)
#include <cstring>
#include <iostream>
using namespace std;
int m, n;
char graph[20][20];
char land;
int max_count;
int dfs_land(int y, int x) {
if (y >= m || y < 0) {
return 0;
}
if (x < 0) {
x = x + n;
}
if (x >= n) {
x = x - n;
}
if (graph[y][x] == land) {
int result = 1;
graph[y][x] = 0;
result += dfs_land(y + 1, x);
result += dfs_land(y - 1, x);
result += dfs_land(y, x + 1);
result += dfs_land(y, x - 1);
return result;
}
return 0;
}
int main() {
while (cin >> m >> n) {
memset(graph, 0, sizeof(graph));
max_count = 0;
for (int i = 0; i < m; i++) {
string s;
cin >> s;
for (int j = 0; j < n; j++) {
graph[i][j] = s[j];
}
}
int x, y;
cin >> y >> x;
land = graph[y][x];
dfs_land(y, x);
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int count = dfs_land(i, j);
if (count > max_count) {
max_count = count;
}
}
}
cout << max_count << endl;
}
return 0;
}
or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up