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;
}