Forrest


私信TA

用户名:dotcpp0717441

访问量:1155

签 名:

等  级
排  名 219
经  验 6126
参赛次数 1
文章发表 58
年  龄 0
在职情况 教师
学  校 优学乐程
专  业

  自我简介:

TA的其他文章

解题思路:BFS

注意事项:

参考代码:

#include<iostream>
#include<queue>
using namespace std;
const int N = 1e3 +10;
char a[N][N];
int n,m,cnt;
bool v[N][N];
struct node{
	int x, y;
};
int d[4][2] = {{-1,0},{0,1},{1,0},{0,-1}};
queue<node> q;
void bfs(int x, int y){
	q.push(node{x,y});
	v[x][y] = true;
	while(!q.empty()){
		node nd = q.front();
		q.pop();
		for(int i = 0; i < 4; i ++){
			int nx = nd.x + d[i][0];
			int ny = nd.y + d[i][1];
			if(nx >= 0 && nx < n && ny >= 0 && ny < m && !v[nx][ny] && a[nx][ny] != '0'){
				v[nx][ny] = true;
				q.push(node{nx,ny});
			}
		}
	}
}
int main()
{
	cin >> n >> m;
	for(int i = 0; i < n; i ++)
		for(int j = 0; j < m; j ++)
			cin >> a[i][j];
	for(int i = 0; i < n; i ++)
		for(int j = 0; j < m; j ++)
			if(!v[i][j] && a[i][j] != '0') {
				bfs(i,j);
				cnt ++;
			}
	cout << cnt;
	return 0;
}


 

0.0分

1 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换万能编程问答  

代码解释器

代码纠错

SQL生成与解释

  评论区