An oilfield is distributed in a region for you. As long as there is a link, it belongs to the same oilfield and several oil fields exist in the region.
Solution: A simple Bfs or dfs can be used to solve the problem. Pay attention to using the mark array to mark the previous steps.
Code:
[Cpp]
<Span style = "font-size: 18px;"> // DFS code (recursive)
# Include <iostream>
# Include <queue>
# Include <cstdio>
# Include <cstring>
Using namespace std;
Const int MAXN = 110;
Int n, m, sum;
Char ch [MAXN] [MAXN];
Int mark [MAXN] [MAXN]; // indicates whether the mark has passed
Int x [8] = {-1,-,-1}; // direction Array
Int y [8] = {0, 1, 1, 0,-1,-1,-1 };
// Search
Void dfs (int I, int j ){
If (mark [I] [j] = 1)
Return;
For (int k = 0; k <8; k ++ ){
If (I + x [k] <0 | I + x [k]> = m | j + y [k] <0 | j + y [k]> = n) // cross-border
Continue;
If (ch [I + x [k] [j + y [k] = '*') // useless characters
Continue;
If (ch [I + x [k] [j + y [k] = '@') {// continue the next Recursion
Mark [I] [j] = 1;
Dfs (I + x [k], j + y [k]);
}
}
}
// Problem handling function
Void solve (){
Int I, j;
Sum = 0;
Memset (mark, 0, sizeof (mark ));
For (I = 0; I <m; I ++ ){
For (j = 0; j <n; j ++ ){
If (ch [I] [j] = '@' & mark [I] [j] = 0 ){
Sum ++;
Dfs (I, j );
}
}
}
Cout <sum <endl;
}
// Main Function
Int main (){
While (scanf ("% d % * c", & m, & n) & m & n ){
For (int I = 0; I <m; I ++ ){
For (int j = 0; j <n; j ++)
Scanf ("% c", & ch [I] [j]);
Getchar ();
}
Solve ();
}
}
// BFS code (queue used)
# Include <iostream>
# Include <queue>
# Include <cstdio>
# Include <cstring>
Using namespace std;
Const int MAXN = 110;
Int n, m, sum;
Char ch [MAXN] [MAXN];
Int mark [MAXN] [MAXN];
Int x [8] = {-1,-,-1 };
Int y [8] = {0, 1, 1, 0,-1,-1,-1 };
Queue <char> q;
// Search
Void Bfs (int I, int j ){
If (q. empty () | mark [I] [j] = 1)
Return;
If (! Q. empty ()){
For (int k = 0; k <8; k ++ ){
If (I + x [k] <0 | I + x [k]> = m | j + y [k] <0 | j + y [k]> = n)
Continue;
If (ch [I + x [k] [j + y [k] = '*')
Continue;
If (ch [I + x [k] [j + y [k] = '@'){
Q. pop (); // the first pair
Q. push ('@'); // incoming pair
Mark [I] [j] = 1;
Bfs (I + x [k], j + y [k]); // you can remove this field and change it to a while loop.
}
}
}
}
// Problem handling function
Void solve (){
Int I, j;
Sum = 0;
Memset (mark, 0, sizeof (mark ));
For (I = 0; I <m; I ++ ){
For (j = 0; j <n; j ++ ){
If (ch [I] [j] = '@' & mark [I] [j] = 0 ){
Sum ++;
Q. push ('@');
Bfs (I, j );
}
}
}
Cout <sum <endl;
}
// Main Function
Int main (){
While (scanf ("% d % * c", & m, & n) & m & n ){
For (int I = 0; I <m; I ++ ){
For (int j = 0; j <n; j ++)
Scanf ("% c", & ch [I] [j]);
Getchar ();
} Www.2cto.com
Solve ();
}
}
</Span>
Author: cgl1079743846