图1(八连块)

输入一个mn列的字符矩阵,统计字符“@”组成多少个八连块。如果两个字符“@”所在的格子相邻(横、竖或者对角线方向),就说它们属于同一个八连块。

Sample Input

1 1 

3 5 
*@*@* 
**@** 
*@*@* 
1 8 
@@****@* 
5 5 
****@ 
*@@*@ 
*@**@ 
@@@*@ 
@@**@ 
0 0

SampleOutput




2


#include"iostream"
using namespace std;
char **map;	
int w,h;
bool selected(int &y,int &x,int n){
	int i[8] = {-1,0,1,1,1,0,-1,-1};
	int j[8] = {-1,-1,-1,0,1,1,1,0};
	if(i[n] + y >= 0 && i[n] + y < h && j[n] + x >= 0 && j[n] + x < w && map[i[n] + y][j[n] + x] == '@'){
		y += i[n];
		x += j[n];
		return true;
	}
	return false;
}
void find8(int y,int x){
	if(map[y][x] == '@'){
		map[y][x] = '*';
		int x1 = x,y1 = y;
		for(int i = 0;i < 8;i++){
			if(selected(y,x,i)){
				find8(y,x);
			}
			x = x1;
			y = y1;
		}
	}
}
void create(){
	map = new char*[h];
	for(int i = 0;i < h;i++){
		map[i] = new char[w];
		for(int j = 0;j < w;j++){
			cin>>map[i][j];
		}
	}
}

int main(){
	while(cin>>w>>h && w && h){
		int a = 2,b = 2;
		int count = 0;
		create();
		for(int i = 0;i < h;i++){
			for(int j = 0;j < w;j++){
				if(map[i][j] == '@'){
					find8(i,j);
					count++;
				}
			}
		}
		cout<<count<<endl;
		for(i = 0;i < h;i++){
			delete[] map[i];
		}
	}
	return 0;
}


原文地址:https://www.cnblogs.com/oleolema/p/12421826.html