1. 程式人生 > >UVa Oil Deposits(dfs)

UVa Oil Deposits(dfs)

和poj 2386一模一樣

簡單的深搜


#include<stdio.h>

char map[105][105];
int m, n;

void dfs(int x, int y) {
  map[x][y] = '*';

  for (int i = -1; i <= 1; i++) {
    for (int j = -1; j <= 1; j++) {
      int dx = i+x, dy = y+j;
      if (dx >= 0 && dy >= 0 && dx < m && dy < n && map[dx][dy] == '@') {
        dfs(dx, dy);
      }
    }
  }
}

int main(void)
{


  while (scanf("%d", &m) != EOF && m) {
    scanf("%d", &n);
    getchar();

    for (int i = 0; i < m; i++) {
      for (int j = 0; j < n; j++) {
        map[i][j] = getchar();
      }
      getchar();
    }

    int ans = 0;
    for (int i = 0; i < m; i++) {
      for (int j = 0; j < n; j++) {
        if (map[i][j] == '@') {
          dfs(i, j);
          ans++;
        }
      }
    }

    printf("%d\n", ans);
  }
  return 0;
}