图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;
}


这个问题可以归类为**的连通问题**,每个“@”字符代表一个中的节点,相邻的“@”(包括对角线)通过边连接。我们需要找出中连通的个数。 ### 解法思路 1. **遍历整个矩阵**,当遇到一个未访问的“@”时,说明我们进入了一个新的连通。 2. 使用 **DFS(深度优先搜索)** 或 **BFS(广度优先搜索)** 来标记这个连通中所有的“@”为已访问。 3. 每次发现一个新的未访问的“@”,计数器加一。 ### 实现代码(Python) ```python def count_eight_connected_blocks(m, n, grid): visited = [[False for _ in range(n)] for _ in range(m)] # 八个方向:上下左右 + 四个对角线 directions = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] def dfs(x, y): visited[x][y] = True for dx, dy in directions: nx, ny = x + dx, y + dy if 0 <= nx < m and 0 <= ny < n: if not visited[nx][ny] and grid[nx][ny] == '@': dfs(nx, ny) count = 0 for i in range(m): for j in range(n): if not visited[i][j] and grid[i][j] == '@': dfs(i, j) count += 1 return count # 读取输入 if __name__ == "__main__": m, n = map(int, input().split()) grid = [] for _ in range(m): grid.append(input().strip()) result = count_eight_connected_blocks(m, n, grid) print(result) ``` ### 代码解释 - `visited` 数组用于记录每个位置是否已经被访问。 - `directions` 表示八个可能的移动方向。 - `dfs` 函数用于递归遍历当前“@”所在的八连,并标记所有相连的“@”为已访问。 - 主循环遍历整个字符矩阵,遇到未访问的“@”就调用 DFS 并增加计数器。 --- ### 示例运行 输入: ``` 5 5 ****@ *@@*@ *@**@ @@@*@ @@**@ ``` 输出: ``` 2 ``` --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值