【问题】
有一个大小为N×M的园子(0≤N,M≤100),雨后积起了水,其中‘W’表示积水,‘ .’表示没有积水。八连通的积水被认为是连接在一起的,是一个水洼。请求出园子里总有多少水洼?(八连通指的是下图中相对W的*的部分)
***
*W*
***
【输入】
输入由一系列的测试样例构成,每一个测试样例由两部分组成。第一部分占据一行,第一个整数表示N,第二个整数表示M。第二部分表示N×M的矩阵。
【输出】
对于每一次输入样例,输出水洼的个数。每一次输出样例另起一行。
【示例输入】
10 12
W........WW.
.WWW.....WWW
....WW...WW.
.........WW.
.........W..
..W......W..
.W.W.....WW.
W.W.W.....W.
.W.W......W.
..W.......W.
【示例输出】
3
-----------------------------------------------------------------------------------------------------------------------------------------------------------------
【示例代码】
//--------------------------------------【程序说明】-------------------------------------------
// 程序说明: Lake Counting
// 程序描述: 搜索
// IDE版本:Visual Studio 2013
// 作者: Arthur Lee
//------------------------------------------------------------------------------------------------
//【1】头文件
#include <fstream>
#include <ctime>
#include <list>
using namespace std;
const int Max_x = 100;
const int Max_y = 100;
#define TIMER
//【2】函数声明
void BreadthFirstSearch(int,int);
void DepthFirstSearch(int,int);
//【3】定义枚举体,在几种方法中切换
enum Method
{
BreadthFirst,
DepthFirst
};
//【4】变量声明
char Lake[Max_x][Max_y];
int row, column;
void main(){
#ifdef TIMER
clock_t start = clock();
#endif // TIMER
ifstream fin("in.txt");
if (fin.fail())
return;
ofstream fout("out.txt");
Method method_temp = Method::DepthFirst;
int nCount;
while (!fin.eof())
{
nCount = 0;
fin >> row >> column;
for (int i = 0; i < row; ++i)
for (int j = 0; j < column; ++j)
fin >> Lake[i][j];
for (int i = 0; i < row; ++i)
for (int j = 0; j < column; ++j){
if (Lake[i][j] == 'W'){
switch (method_temp)
{
case BreadthFirst:
BreadthFirstSearch(i, j);
++nCount;
break;
case DepthFirst:
DepthFirstSearch(i, j);
++nCount;
break;
default:
break;
}
}
}
fout << "the number of lake is : " << nCount;
fout << "\n";
}
#ifdef TIMER
clock_t end = clock();
double duration = (double)(end - start);
fout << "runtime : " << duration << "ms" << endl;
#endif // TIMER
fout.close();
}
//【5】函数实现
bool IsStepLegal(int x, int y,int dx,int dy ){
if (dx == 0 && dy == 0)
return false;
if (x + dx >= row || x + dx < 0 || y + dy >= column || y + dy < 0)
return false;
if (Lake[x + dx][y + dy] == '.')
return false;
return true;
}
void DepthFirstSearch(int a,int b){
if (Lake[a][b] == '.')
return;
Lake[a][b] = '.';
for (int i = -1; i <= 1; ++i)
for (int j = -1; j <= 1; ++j){
if (IsStepLegal(a, b, i, j))
DepthFirstSearch(a + i, b + j);
}
return;
}
void BreadthFirstSearch(int a, int b){
list<int> list_temp;
list_temp.push_back(a);
list_temp.push_back(b);
int a_temp, b_temp;
while (!list_temp.empty()){
a_temp = list_temp.front();
list_temp.pop_front();
b_temp = list_temp.front();
list_temp.pop_front();
for (int i = -1; i <= 1; ++i)
for (int j = -1; j <= 1; ++j){
if (IsStepLegal(a_temp, b_temp, i, j)){
Lake[a_temp + i][b_temp + j] = '.';
list_temp.push_back(a_temp + i);
list_temp.push_back(b_temp + j);
}
}
}
return;
}