简单搜索。DFS求图有几个连通分量。

CODE:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
using namespace std;

const int SIZE = 110;
const int move[8][2] = {{-1,-1}, {-1,0}, {-1,1}, {0,1}, {0,-1}, {1,1}, {1,0}, {1,-1}};
char maze[SIZE][SIZE];
int N, M;


int check(int r, int c)
{
    if(maze[r][c] != '*' && r >= 0 && c >= 0 && r < N && c < M)
        return 1;
    return 0;
}


void dfs(int r, int c)
{
    maze[r][c] = '*';
    for(int i = 0; i < 8; i++)
    {
       int rr = r+move[i][0];
       int cc = c+move[i][1];
       if(check(rr, cc))
       {
            dfs(rr, cc);
       }
    }
}



int main()
{
    int i, j;
    int cnt;
    while(~scanf("%d%d", &N, &M), N, M)
    {
        cnt = 0;
        getchar();
        for(i = 0; i < N; i++)    scanf("%s", maze[i]);
        for(i = 0; i < N; i++)
        {
            for(j = 0; j < M; j++)
            {
                if(maze[i][j] == '@')
                {
                    dfs(i, j);
                    cnt++;
                }
            }
        }
        printf("%d\n", cnt);
    }
    return 0;

} 

posted on 2012-08-19 15:58  有间博客  阅读(131)  评论(0编辑  收藏  举报