ACM-ZOJ 2412 DFS 深度优先搜索

//2012-10-10 10:58:45	 Accepted	2412	C++	0ms	200kb
#include 
#include 
#include 
using namespace std;

const int MAX(55);
char map[MAX][MAX];
int flag[MAX][MAX];  //对应是否访问过
int M, N;

void DFS( int x, int y ) {
    flag[x][y] = 1;
    if (x < 0 || y < 0 || x >=M || y >= N )  return ;  //判断是否是边界

    //上 x - 1
    if( flag[x - 1][y] != 1 &&
        map[x][y] != 'C' && map[x][y] != 'D' && map[x][y] != 'F' && map[x][y] != 'I' &&
        map[x - 1][y] != 'A' && map[x - 1][y] != 'B' && map[x - 1][y] != 'F' && map[x - 1][y] != 'G'
        )  DFS(x - 1, y);

    //下 x + 1
    if ( flag[x + 1][y] != 1 &&
         map[x][y] != 'A' && map[x][y] != 'B' && map[x][y] != 'F' && map[x][y] != 'G' &&
         map[x + 1][y] != 'C' && map[x + 1][y] != 'D' && map[x + 1][y] != 'F' && map[x + 1][y] != 'I'
        )  DFS(x + 1, y);

    //左 y - 1
    if ( flag[x][y - 1] != 1 &&
         map[x][y] != 'B' && map[x][y] != 'D' && map[x][y] != 'E' && map[x][y] != 'J' &&
         map[x][y - 1] != 'A' && map[x][y - 1] != 'C' && map[x][y - 1] != 'E' && map[x][y - 1] != 'H'
        )  DFS(x, y - 1);

    //右 y + 1
    if ( flag[x][y + 1] != 1 &&
         map[x][y] != 'A' && map[x][y] != 'C' && map[x][y] != 'E' && map[x][y] != 'H' &&
         map[x][y + 1] != 'B' && map[x][y + 1] != 'D' && map[x][y + 1] != 'E' && map[x][y + 1] != 'J'
        )  DFS(x, y + 1);
}

int main() {
    while ( scanf("%d%d", &M, &N) && M >= 0 && N >= 0) {
        int i(0), j(0);
        memset(map, 0, sizeof(map));
        memset(flag, 0, sizeof(flag));
        for ( i = 0; i != M; ++i )
            scanf("%s", map[i]);

        int answer(0);
        for ( i = 0; i != M; ++i )
            for ( j = 0; j != N; ++j )
                if (flag[i][j] == 0){
                    ++answer;
                    DFS(i, j);
                }

        printf("%d\n", answer);
    }
}

 

你可能感兴趣的:(ACM,c++,c)