[ Aizu - 0118 ]

这道题类似于联通图问题,将联通的归成一个,数一下总共有几个即可。

因为题目告诉不会有空格,所以排除标记用空格表示即可。

Sample Input

10 10
####*****@
@#@@@@#*#*
@##***@@@*
#****#*@**
##@*#@@*##
*@@@@*@@@#
***#@*@##*
*@@@*@@##@
*@*#*@##**
@****#@@#@
0 0

Sample Output

33

题解

#include<iostream>
#include<string>
#include<cstdio>
#include<cstring>
#include<queue>
#include<map>
#include<set>
#include<algorithm>
#include<cmath>
#include<cstdlib>
using namespace std;

int m, n;
char garden[105][105];
int d[4][2] = {
    {0, -1},
    {1, 0},
    {0, 1},
    {-1, 0},
};

void dfs(int x, int y, char c)
{
    if(garden[x][y] == c){
        garden[x][y] = ' ';

        for (int i = 0; i < 4; i++){
            int nx = x + d[i][1];
            int ny = y + d[i][0];
            if (0 <= nx && nx < n && 0 <= ny && ny < m && garden[nx][ny] != ' ')
                dfs(nx, ny, c);
        }
    }
}

int main(void)
{
    while(~scanf("%d%d", &n, &m) && m+n){
        getchar();
        memset(garden, 0, sizeof(garden));

        for (int i = 0; i < n; i++){
            for (int j = 0; j < m; j++)
                scanf("%c", &garden[i][j]);
            getchar();
        }

        int sum = 0;
        for (int i = 0; i < n; i++){
            for (int j = 0; j < m; j++){
                if (garden[i][j] != ' '){
                    dfs(i, j, garden[i][j]);
                    sum++;
                }
            }
        }

        cout << sum << endl;
    }

    return 0;
}