踏青

Description

 

小白和他的朋友周末相约去召唤师峡谷踏青。他们发现召唤师峡谷的地图是由一块一块格子组成的,有的格子上是草丛,有的是空地。草丛通过上下左右 4 个方向扩展其他草丛形成一片草地,任何一片草地中的格子都是草丛,并且所有格子之间都能通过上下左右连通。如果用'#'代表草丛,'.'代表空地,下面的峡谷中有 2 片草地。

##..

..##

处在同一个草地的 2 个人可以相互看到,空地看不到草地里面的人。他们发现有一个朋友不见了,现在需要分头去找,每个人负责一片草地,想知道他们至少需要多少人。

Input

 

第一行输入 n, m (1 ≤ n,m ≤ 100) 表示峡谷大小。

接下来输入 n 行字符串表示峡谷的地形。

Output

 

输出至少需要多少人。

 

Sample Input 1 

 

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

 

Sample Output 1

 

5

     

此题就是一个连通块的问题深搜,广搜都可以实现,解决。 

 

深搜代码:

#include <bits/stdc++.h>
using namespace std;
int n, m, tot;
string maze[1001];
bool vis[1001][1001];
const int dir[4][2] =  {{-1, 0}, {0, -1}, {1, 0}, {0, 1}};//控制四个方向 

bool in(int x, int y) {
	return x >= 0 && x < n && y >= 0 && y < m;//检查是否在图中 
}

int dfs(int x, int y) {
	for(int i = 0; i < 4; i++) {
		int tx = x + dir[i][0];
		int ty = y + dir[i][1];
		if(in(tx,ty) && !vis[tx][ty] && maze[tx][ty] == '#') {
			vis[tx][ty] = 1;
			dfs(tx,ty);
		}
	}
}

int main() {
	int k = 0;
	cin >> n >> m;
	for(int i = 0; i < n; i++) {
		cin >> maze[i];
	}
	for(int i = 0; i < n; i++) {
		for(int j = 0; j < m; j++) {
			if(maze[i][j] == '#' && !vis[i][j]) {
				vis[i][j] = 1;
				dfs(i, j);//深搜 
				tot++;
			}
		}
	}
	cout << tot << endl;
	return 0;
}

 

广搜代码:

#include <iostream>
#include <queue>
using namespace std;
const int maxn = 110;
string grass[maxn];
bool vis[maxn][maxn];
struct node {
	int x, y;
	node() {}
	node(int _x, int _y) {
		x = _x;
		y = _y;
	}
};
const int dir[4][2] = {{1,0}, {-1,0}, {0,1}, {0,-1}};//模拟方向 
int n, m;

bool in(int x, int y) {
	return 0 <= x && x < n && 0 <= y && y < m;//判断是否在图中 
}

void bfs(int x, int y) {
	queue<node> que;
	que.push(node(x, y));
	vis[x][y] = 1;//标记 
	while(!que.empty()) {
		for(int i = 0; i < 4; i++) {
			int tx = que.front().x + dir[i][0];
			int ty = que.front().y + dir[i][1];
			if(in(tx, ty) && grass[tx][ty] == '#' && !vis[tx][ty]) {
				que.push(node(tx, ty));//入队,查找相邻块 
				vis[tx][ty] = 1;//进行标记 
			}
		}
		que.pop();//出队 
	}
}

int main() {
	cin >> n >> m;//输入 
	for(int i = 0; i < n; i++) {
		cin >> grass[i];
	}

	int tot = 0;
	for(int i = 0; i < n; i++) {
		for(int j = 0; j < m; j++) {
			if(grass[i][j] == '#' && !vis[i][j]) {//如果此刻grass[i, j]为"#",并且没有标记过; 
				tot++;//个数++ 
				bfs(i, j);//广搜 
			}
		}
	}
	cout << tot;//输出 

	return 0;
}

  O(∩_∩)O好了

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值