红与黑

#include
using namespace std;

const int N = 25;

char g[N][N];
bool st[N][N];
int n, m;
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};

int dfs(int x, int y)
{
    int cnt = 1;
    
    st[x][y] = true;
    for(int i = 0; i < 4; i++)
    {
        int a = x + dx[i], b = y + dy[i];
        if(a < 0 || a >= n || b < 0 || b>= m) continue;
        if(g[a][b] != '.') continue;
        if(st[a][b]) continue;
        
        cnt += dfs(a, b);
    }
    return cnt;
}

int main()
{
    while(cin >> m >> n, n || m)
    {
        for(int i = 0; i < n; i++) scanf("%s", g[i]);
        
        int x, y;
        for(int i = 0; i < n; i++)
            for(int j = 0; j < m; j++)
                if(g[i][j] == '@')
                {
                    x = i;
                    y = j;
                    break;
                }
                
        memset(st, 0, sizeof st);
        cout << dfs(x, y) << endl;
    }
    
    return 0;
}

你可能感兴趣的:(红与黑)