Outing connected block problem dfs

Outing

Description

Xiaobai and his friend met on the weekend to go outing in Summoner's Canyon. They found that the map of Summoner's Canyon was made up of grids, some of which were covered with grass, and some were open spaces. The grasses expand other grasses in 4 directions up, down, left, and right to form a grass. The grids in any piece of grass are grasses, and all grids can be connected up, down, left, and right. If you use'#' to represent grass and'.' to represent open land, there are 2 grasslands in the canyon below.

##…

…##

Two people in the same grassland can see each other, but the people in the grassland cannot be seen in the open space. They found that one of their friends had disappeared, and now they need to find them separately. Everyone is in charge of a piece of grass, and they want to know how many people they need at least.

Input

Enter n, m (1 ≤ n, m ≤ 100) in the first line to indicate the size of the canyon.

Next, enter n lines of strings to represent the terrain of the canyon.

Output

At least how many people are needed to output.

Sample Input 1

5 6
.#…
…#…
…#…#
…##.
.#…
Sample Output 1

5

#include<bits/stdc++.h>
using namespace std;
long long cnt=0;//cnt的数值可能会大于int类型
int n,m,nx[4][2]={
    
    {
    
    0,1},{
    
    1,0},{
    
    -1,0},{
    
    0,-1}};//运用于方位的转化 
int vis[110][110]={
    
    0};
char mp[110][110];

bool in(int x,int y){
    
    
	return x>-1&&x<n&&y>-1&&y<m;//运用于移动后的位置是否合法 
}

void dfs(int x,int y){
    
    
	for(int i=0;i<=3;i++){
    
    
		int nowx=x+nx[i][0];//进行方位转化 
		int nowy=y+nx[i][0];
		if(in(nowx,nowy)&&mp[nowx][nowy]=='#'&&!vis[nowx][nowy]){
    
    //是否出局 是否能放 是否已经被放了 
			vis[nowx][nowy]=1;
			dfs(nowx,nowy);//进行dfs搜索 
		}
	}
}


int main(){
    
    
	cin>>n>>m;
	for(int i=0;i<n;i++){
    
    
		cin>>mp[i];
	}
	for(int i=0;i<n;i++){
    
    
		for(int j=0;j<m;j++){
    
    
			if(mp[i][j]=='#'&&!vis[i][j]){
    
    //能放就进行cnt++ 
			cnt++;
			vis[i][j]=1;
			dfs(i,j);	
			}
		}
	}
	cout<<cnt;
	return 0;	
} 

Guess you like

Origin blog.csdn.net/qq_47874905/article/details/109011751