Test instructions
In the Rectangle orchard of H * W, there are three kinds of fruit trees in apple, pear and tangerine, and the same fruit trees in the adjacent (upper and lower left and right) belong to the same region, and the fruit tree distribution in orchard is given.
Input:
Multiple sets of data, the first behavior of each group of data two integers h,w (h <=, W <=), h = 0 and W = 0 for the input end. The following H-row w columns indicate orchard fruit tree distribution, Apple is @, pear is #, Tangerine is *.
Output:
For each set of data, output the number of its regions.
#include <cstdio> #include <vector> #include <queue> #include <string> #include <map># include<iostream> #include <cstring> #include <algorithm>using namespace std;typedef long long LL; const int INF = 0x7fffffff;const int MAXN = 1e5 + 10; #define MAX_W 100#define max_h 100char farm[max_w][max_h];int W, h;const int direction[4][2] = {{-1, 0}, {1, 0}, { 0,-1}, {0, 1},}; void Dfs (int x, int y, char tree) {Farm[x][y] = ' x '; for (int i = 0; i < 4; ++i) {int NX = x + direction[i][0]; int ny = y + direction[i][1]; if (NX >= 0 && NX < W && NY >= 0 && NY < H && Farm[nx][ny] = = tree) { DFS (NX, NY, tree); }}} int main () {while (CIN >> H >> W, w > 0) {int res = 0; int x, y; for (y = 0, y < H; ++y) {for (x = 0; x < W; ++x) {cin >> farm[x][y]; }} for (y = 0, y < H; ++y) {for (x = 0; x < W; ++x{if (farm[x][y]! = ' x ') {dfs (x, y, farm[x][y]); ++res; }}} cout << res << Endl; } return 0;}
AOJ 0118 Property Distribution "DFS"