UVa 657 The die is cast(DFS)

双层DFS, X数量绝对不超过6个,所以毫无疑问,双层就可以解决掉!

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;

const int N = 55;
int n, m, numx, cnt, ans[N*N];
int a[] = { 0, 0, 1, -1 };
int b[] = { 1, -1, 0, 0 };
char g[N][N];

void dfsx ( int x, int y ) {
    g[x][y] = '*';
    for ( int i = 0; i < 4; ++i ) {
        int xx = x + a[i], yy = y + b[i];
        if ( g[xx][yy] == 'X' ) dfsx( xx, yy );
    }
}
void dfs( int x, int y ) {
    if ( g[x][y] == 'X' ) {
        numx++;
        dfsx ( x, y );
    }
    g[x][y] = '.';
    for ( int i = 0; i < 4; ++i ) {
        int xx = x + a[i], yy = y + b[i];
        if ( g[xx][yy] == 'X' || g[xx][yy] == '*' ) dfs( xx, yy );
    }
}
int main()
{
    int icase = 1;
    while ( scanf("%d%d", &m, &n) != EOF && ( n || m ) ) {
        memset( g, '\0', sizeof(g) );
        memset( ans, 0, sizeof(ans) );
        cnt = 0;
        for ( int i = 0; i < n; ++i )
            scanf("%s", g[i]);
        for ( int i = 0; i < n; ++i )
            for ( int j = 0; j < m; ++j ) {
               if ( g[i][j] == 'X' || g[i][j] == '*' ) {
                   numx = 0;
                   dfs( i, j );
                   ans[cnt++] = numx;
               }
            }
        sort( ans, ans + cnt );
        printf("Throw %d\n%d", icase++, ans[0]);
        for ( int i = 1; i < cnt; ++i ) printf(" %d", ans[i]);
        printf("\n\n");
    }
}


你可能感兴趣的:(UVa 657 The die is cast(DFS))