输入格式:
第一行输入两个整数n,m(3≤n,m≤100)
其后n行,每行m个字符,字符有'*'和'#'两种。'*'代表城区边界或主干道,'#'代表网格单元内区域。
输出格式:
输出一行一个整数,代表地图中的网格单元个数。
输入样例:
3 7
*******
*##*##*
*******
输出样例:
2
思路:
dfs搜索嘛,对每个点进行搜索,然后沿着这个点的八个方向进行dfs,如果他临近的点是可以走的就把这个点都标记上走过了,并且对邻近的点进行dfs搜索,一直到这一个代码块最外面一圈的临近没有可以走的了,代表这个块结束了,就++
代码
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <string>
#include <map>
#include <set>
#include<tr1/unordered_map>
#include <tr1/unordered_set>
using namespace std::tr1;
using namespace std;
typedef long long ll;
const int N = 110;
const int MOD = 1e9 + 7;
int n, m, cnt = 0;
char s[N][N];
int flag[N][N];
int Go[8][2] = {-1,0, -1,1, 0,1, 1,1, 1,0, 1,-1, 0,-1, -1,-1};
void dfs(int x, int y) {
int ty, tx;
for (int i = 0; i < 8; i++) {
tx = x + Go[i][0];
ty = y + Go[i][1];
if (tx < 0 || tx >= n || ty < 0 || ty >= m) continue;
if (flag[tx][ty] == false && s[tx][ty] == '#') {
flag[tx][ty] = true;
dfs(tx, ty);
}
}
return;
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 0; i < n; i++) {
scanf("%s", s[i]);
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (flag[i][j] == false && s[i][j] == '#') {
dfs(i, j);
cnt++;
}
}
}
printf("%d", cnt);
return 0;
}