DFS exercise - outing (DFS seeking connected blocks)

 

Suantoujun and his friends went to Summoner's Rift for a weekend outing. They found that the map of Summoner's Rift is made up of grids, some of which are grass and some are open spaces. Grass clumps expand other clumps in four directions, up, down, left, and right, to form a piece of grass. Any grid in a piece of grass is a clump, and all grids can be connected through up, down, left, and right. If it is used to '#'represent grass, it '.'represents open space, and there are 2 grass fields in the canyon below.

1##..

2..##

2 people in the same grass can see each other, but the people in the grass cannot be seen in the open space. They found that a friend was missing, and now they need to find them separately. Each person is responsible for a piece of grass. Garantou-jun wants to know how many people they need at least.

input format

The first line of input n, m (1≤n,m≤100) represents the size of the canyon.

Next enter n lines of strings representing the terrain of the canyon.

input format

Output at least how many people are needed.

Sample input copy

5 6
.#....
..#...
..#..#
...##.
.#....

Sample output copy

5

 


Ideas:

DFS finds connected blocks and marks all the grasses in the same block

 

Code:

#include<iostream>
using namespace std;
char s[105][105];
int cot;
int dir[4][2] = {
   
   {0,1},{0,-1},{1,0},{-1,0}};
int n,m;

void dfs(int x,int y)
{
    s[x][y]='.';  //将草丛置空
	for(int i=0;i<4;i++)
    {
        int tx = x + dir[i][0];
        int ty = y + dir[i][1];
        if(s[tx][ty]=='#')
            dfs(tx,ty);
    }
}

//还要求联通块
int main()
{
    std::ios::sync_with_stdio(false);
    cin.tie(0);
    cin>>n>>m;
    for(int i=0;i<n;i++)
        for(int j=0;j<m;j++)
			cin>>s[i][j];
	for(int i=0;i<n;i++)
        for(int j=0;j<m;j++)
        {
            if(s[i][j]=='#')
            {
                cot++;
                dfs(i,j);
            }
        }
    cout<<cot<<endl;
    return 0;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326312981&siteId=291194637
dfs