[Outing] C ++ solution to a problem

Title Description

White and his friends went to meet Summoner Canyon weekend outing. They found Summoner Canyon map is composed of a piece of lattice, and some is grass, plenty of open space on the grid. Forming a lawn grass extended by four vertical and horizontal directions other grass, a grass in any grid is grass, and can communicate among all the grid by the vertical and horizontal. If the '#' for grass, '' represents a space, there are the following two valleys grass.

##…
…##

2 people are in the same meadow can see each other, clearing the grass can not see the people inside. They found that a friend was gone, and now need to look separately, each person in charge of a meadow, want to know how many people they need at least.

Entry

The first input line n, m (1 ≤ n, m ≤ 100) indicates the size of the canyon.
The next input character string represented by n lines canyon terrain.

Export

How many people need to output at least.

Sample

Entry

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

Export

5

Thinking

Represents a two-dimensional array of terrain, enter the circulation, for each unlabeled grass, four directions recursive encountered unlabeled grass is marked, returns encountered space
Show

answer

#include <iostream>
using namespace std;
int n, m, map[101][101];
void F(const int& x, const int& y){
	if(0 <= x && x < n && 0 <= y && y < m && map[x][y] == 0) map[x][y] = 2;
	else return;
	F(x+1, y); F(x, y+1);
	F(x-1, y); F(x, y-1);
}
int main(){
	cin >> n >> m;
	for(int i = 0; i < n; ++i)
		for(int j = 0; j < m; ++j){
			char ch;
			cin >> ch;
			switch(ch){
				case '.': map[i][j] = 1; break;
				case '#': map[i][j] = 0; break;
			}
		}
	int ans = 0;
	for(int i = 0; i < n; ++i)
		for(int j = 0; j < m; ++j)
			if(map[i][j] == 0){
				F(i, j);
				++ans;
			}
	cout << ans << endl;
	return 0;
}
Released six original articles · won praise 5 · Views 757

Guess you like

Origin blog.csdn.net/weixin_45425652/article/details/104036879