poj 2386 Lake Counting

#include <iostream>
#include <string>
using namespace std;
const int MAX = 110;
char matrix[MAX][MAX];
int n, m, vis[MAX][MAX], ans;
//每一个点的八个方向坐标的增减! 
int dir[8][2] = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}};

//矩阵的输入 
void init()
{
     int i, j; 
     for (i = 0; i < n; i++){
          getchar();
          for (j = 0; j < m; j++){
               scanf("%c", &matrix[i][j]);
          }
     }
     return ;
}

//进行深度搜索! 
void dfs(int x, int y)
{
     int i, tmpx, tmpy;
     vis[x][y] = 1;
     for (i = 0; i < 8; i++){
          tmpx = x + dir[i][0];
          tmpy = y + dir[i][1];
          if (tmpx >= 0 && tmpx < n && tmpy >= 0 && tmpy < m && matrix[tmpx][tmpy] == 'W' && !vis[tmpx][tmpy]){
              dfs(tmpx, tmpy);
          }
     }
}


int main()
{
    int i, j;
    while (scanf("%d%d", &n, &m) != EOF){
          ans = 0;
          memset(vis, 0, sizeof(vis));
          init();
          for (i = 0; i < n; i++){
              for (j = 0; j < m; j++){
                  if (matrix[i][j] == 'W' && !vis[i][j]){
                      dfs(i, j);
                      ans++;
                  }
              }
          }
          cout << ans << endl;
    }
    
    system("pause");
}

你可能感兴趣的:(poj 2386 Lake Counting)