POJ 2386 Lake Counting

扫全图
遇到没标记的水开始DFS,并++Ans
对八个方向坐标增量打表以减少码量

#include <iostream>
#include <string>

using namespace std;

const int MAXN=111;
const int MAXM=111;

string input;
int N, M;
int isW[MAXN][MAXM];
bool Vis[MAXN][MAXM];
int dx[8]={-1, -1, -1, 0, 0, 1, 1, 1};
int dy[8]={1, 0, -1, -1, 1, 0, -1, 1};
int Ans=0;

bool In(int x, int y){
	return (x>=1 && x<=N && y>=1 && y<=M);
}

void DFS(int x, int y){
	Vis[x][y]=true;
	for(int i=0, xx, yy;i<8;++i){
		xx=x+dx[i];yy=y+dy[i];
		if(In(xx, yy) && !Vis[xx][yy] && isW[xx][yy])
			DFS(xx, yy);
	}
}

int main(){
	ios_base::sync_with_stdio(false);
	
	cin >> N >> M;
	for(int i=1;i<=N;++i){
		cin >> input;
		for(int j=1;j<=M;++j){
			isW[i][j]=(input[j-1]=='W');
		}
	}
	
	for(int i=1;i<=N;++i){
		for(int j=1;j<=M;++j){
			if(!Vis[i][j] && isW[i][j]){
				DFS(i, j);
				++Ans;
			}
		}
	}
	
	cout << Ans << endl;
	
	return 0;
}

/*
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

*/
原文地址:https://www.cnblogs.com/Pickupwin/p/9027761.html