poj 1979 Red and Black

目录

知识点:DFS

solution

#include <cstdio>

int W, H;
char tile[25][25];
int pos_x, pos_y;
int sh_x[4] = {0, 0, -1, 1};
int sh_y[4] = {1, -1, 0, 0};
int res = 0;

void solve(int x, int y)
{
  tile[y][x] = '#';
  res++;
  
  for (int i=0;i<4;i++) {
    int new_x = x + sh_x[i];
    int new_y = y + sh_y[i];
    if (new_x >= 0 && new_x <W && new_y >=0 && new_y < H && tile[new_y][new_x] != '#') {
      solve(new_x, new_y);
    }
  }
}

int main()
{

  while (1)
  {
    scanf("%d %d", &W, &H);
    getchar();
    if (!W && !H) {
      break;
    }

    for (int i = 0; i < H; i++) {
      fgets(tile[i], 25, stdin);
      tile[i][W] = '#';
    }

    for (int i=0;i<H;i++) {
      for (int j=0;j<W;j++) {
        if (tile[i][j] == '@') {
          pos_x = j;
          pos_y = i;
        }
        if (i==H-1) {
          tile[H][j] = '#';
        }
      }
    }

    solve(pos_x, pos_y);
    printf("%d\n", res);
    res = 0;
  }
  return 0;
}