HDU 2952 Counting Sheep

Description

一个网格图,上下左右算一块 问总共有几块

Alogrithm

搜索 DFS

Code

#include <cstdio>
#include <iostream>
#include <stack>
using namespace std;
const int maxh = 100;
const int maxw = 100;
const int dx[4] = {0, 0, 1, -1};
const int dy[4] = {1, -1, 0, 0};
struct P
{
  int x, y;
};
void solve()
{
  int h, w;
  cin >> h >> w;
  char g[maxh][maxw];
  for (int i = 0; i < h; i++)
    scanf("%s", g[i]);
  int ans = 0;
  for (int i = 0; i < h; i++)
    for (int j = 0; j < w; j++)
      if (g[i][j] == '#')
      {
        ans++;
        stack<P> s;
        P now;
        now.x = i;
        now.y = j;
        s.push(now);
        while (!s.empty())
        {
          now = s.top();
          s.pop();
          for (int k = 0; k < 4; k++)
          {
            int x = now.x + dx[k];
            int y = now.y + dy[k];
            if (x >= 0 && x < h && y >= 0 && y < w && g[x][y] == '#')
            {
              g[x][y] = '.';
              P t;
              t.x = x;
              t.y = y;
              s.push(t);
            }
          }
        }
      }
  cout << ans << endl;
}
int main()
{
  int t;
  cin >> t;
  for (int i = 0; i < t; i++)
    solve();
}

你可能感兴趣的:(HDU 2952 Counting Sheep)