题目
传送门
输入:
12 12
.##########
.
#
..........#
#
..#
...##
..#
#
.##
..#
..#
.#
#
......#
.#
.#
#
....#
..#
..#
#
...#
.#
....#
#
..#
...#
...#
.#
..#
.#
....#
#
....#
.....#
#
.........#
.
.#########
..
输出
4
输入
12 10
.#####
....
#
.....#
...
#
..#
..#
...
#
.#
.#
.#
...
#
..#
..#
...
.#
...#
....
..###
.....
......#
...
.##
..#
.#
..
#
..#
..#
...
.##
.......
..........
输出
4
题意:n行,m列字符问有几个黑色连通块 思路:直接跑dfs
AC code
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<map>
#include<sstream>
#include<queue>
#include<stack>
using namespace std
;
char a
[120][120];
int n
,m
,s
=0;
void dfs(int x
,int y
)
{
if(x
<0||x
>=n
||y
<0||y
>=m
)return ;
a
[x
][y
]='.';
if(a
[x
+1][y
]=='#')dfs(x
+1,y
);
if(a
[x
-1][y
]=='#')dfs(x
-1,y
);
if(a
[x
][y
+1]=='#')dfs(x
,y
+1);
if(a
[x
][y
-1]=='#')dfs(x
,y
-1);
if(a
[x
+1][y
+1]=='#')dfs(x
+1,y
+1);
if(a
[x
+1][y
-1]=='#')dfs(x
+1,y
-1);
if(a
[x
-1][y
-1]=='#')dfs(x
-1,y
-1);
if(a
[x
-1][y
+1]=='#')dfs(x
-1,y
+1);
}
int main()
{
ios
::sync_with_stdio(0);
cin
>>n
>>m
;
for(int i
=0;i
<n
;i
++)
cin
>>a
[i
];
for(int i
=0;i
<n
;i
++)
for(int j
=0;j
<m
;j
++)
{
if(a
[i
][j
]=='#')
{s
++;
dfs(i
,j
);}
}
printf("%d",s
);
}
转载请注明原文地址:https://blackberry.8miu.com/read-10452.html