此题本质:求无向图的连通分量数。=>使用深度优先搜索(mark[]标记数组)(在main的调用DFS的循环中,循环几次就有几个连通分量)
-
题目描述:
-
The GeoSurvComp geologic survey company is responsible for detecting underground oil deposits. GeoSurvComp works with one large rectangular region of land at a time, and creates a grid that divides the land into numerous square plots. It then analyzes each plot separately, using sensing equipment to determine whether or not the plot contains oil. A plot containing oil is called a pocket. If two pockets are adjacent, then they are part of the same oil deposit. Oil deposits can be quite large and may contain numerous pockets. Your job is to determine how many different oil deposits are contained in a grid.
-
输入:
-
The input file contains one or more grids. Each grid begins with a line containing m and n, the number of rows and columns in the grid, separated by a single space. If m = 0 it signals the end of the input; otherwise 1 <= m <= 100 and 1 <= n <= 100. Following this are m lines of n characters each (not counting the end-of-line characters). Each character corresponds to one plot, and is either `*', representing the absence of oil, or `@', representing an oil pocket.
-
输出:
-
For each grid, output the number of distinct oil deposits. Two different pockets are part of the same oil deposit if they are adjacent horizontally, vertically, or diagonally. An oil deposit will not contain more than 100 pockets.
-
样例输入:
-
1 1 * 3 5 *@*@* **@** *@*@* 1 8 @@****@* 5 5 ****@ *@@*@ *@**@ @@@*@ @@**@ 0 0
-
样例输出:
-
0 1 2 2
//本质!求连通分量数
#include <iostream>
#define MAXSIZE 100
using namespace std;
int m,n;
bool mark[MAXSIZE][MAXSIZE];
bool buf[MAXSIZE][MAXSIZE];
void DFS(int i,int j){
if (i<0||j<0||i>=m||j>=n){//illegal ordinate
return;//缩回去
}
if (mark[i][j]==true||buf[i][j]==false){//相当于指针为空
return;//缩回去
}
//visit
mark[i][j]=true;
//DFS
DFS(i-1,j);
DFS(i+1,j);
DFS(i,j-1);
DFS(i,j+1);
DFS(i-1,j-1);
DFS(i-1,j+1);
DFS(i+1,j-1);
DFS(i+1,j+1);
}
int main(){
char c;
int count;
while (cin>>m>>n,m){
//input
for(int i=0;i<m;i++){
for (int j=0;j<n;j++){
cin>>c;
if (c=='*')//no oil
buf[i][j]=false;
if (c=='@')//oil
buf[i][j]=true;
}
}
//initiate
count=0;
for (int i=0;i<m;i++){
for (int j=0;j<n;j++){
mark[i][j]=false;
}
}
//search
for (int i=0;i<m;i++){
for (int j=0;j<n;j++){
if (mark[i][j]==false&&buf[i][j]==true){
DFS(i,j);
count++;
}
}
}
//output
cout<<count<<endl;
}
return true;
}