BFS队列求助!!!
查看原帖
BFS队列求助!!!
725794
BBY123楼主2022/9/13 09:36
#include<bits/stdc++.h>
#define N 1000
using namespace std;
struct node{
	int x,y;
};
int n,m,v[N][N],ans;
char a[N][N];
int dir[4][2]={{0,1},{0,-1},{1,0},{1,-1}};
void bfs(int x,int y){
	deque<node> q;
	node t;
	t.x=x;
	t.y=y;
	q.push_back(t);
	v[x][y]=1;
	while(!q.empty()){
		int tx,ty;
		for(int i = 0;i < 4;i++){
			tx=x+dir[i][0];
			ty=y+dir[i][1];
			if(a[tx][ty]!='0'&&v[tx][ty]==0&&tx<=n&&ty<=m){
				t.x=x;
				t.y=y;
				q.push_back(t);
				v[tx][ty]=1;
			}
		}
		q.pop_front();
	}
}
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(a[i][j]!='0'&&v[i][j]==0){
				bfs(i,j);
				ans++;
			}
	cout<<ans;
	return 0;
}
2022/9/13 09:36
加载中...