题目链接
Property Distribution Aizu - 0118
思路
dfs
时间复杂度
$$ 每组O(NM) $$
代码
#include <cstdio>
using namespace std;
const int MAXN = 105;
int n, m;
char s[MAXN][MAXN];
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
bool check(int x, int y) {
if (1 <= x && x <= n && 1 <= y && y <= m) {
return true;
} else {
return false;
}
}
void dfs(int x, int y, char c) {
s[x][y] = 'W';
for (int i = 0; i < 4; i++) {
int xx = x + dx[i];
int yy = y + dy[i];
if (check(xx, yy) && s[xx][yy] == c) {
dfs(xx, yy, c);
}
}
}
int main() {
while (scanf("%d%d", &n, &m), n + m) {
for (int i = 1; i <= n; i++) {
scanf("%s", s[i] + 1);// no &
}
int ans = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (s[i][j] == '#' || s[i][j] == '@' || s[i][j] == '*') {
ans++;
dfs(i, j, s[i][j]);
}
}
}
printf("%d\n", ans);
}
return 0;
}