题目大意:
统计图中具有相同元素的连通块个数,需保证该连通块周围的所有元素都比连通块元素小。
思路:DFS入门题
#include <iostream>
#include <cstdio>
using namespace std;
int dx[] = {-1,-1,-1, 0, 0, 1, 1, 1};
int dy[] = {-1, 0, 1,-1, 1,-1, 0, 1};
int n, m, flag;
int v[710][710], a[710][710];
int check(int i, int j)
{
if(i >= 0 && i < n && j >= 0 && j < m)
return 1;
return 0;
}
void dfs(int i, int j)
{
int x, y;
for (int k = 0; k != 8; ++k)
{
x = i + dx[k];
y = j + dy[k];
if (check(x,y))
{
if (a[x][y] > a[i][j])
flag = 0;
if (!v[x][y] && a[x][y] == a[i][j])
{
v[x][y] = 1;
dfs(x,y);
}
}
}
}
int main()
{
scanf("%d %d", &n, &m);
for (int i = 0; i != n; ++i)
for (int j = 0; j != m; ++j)
{
scanf("%d",&a[i][j]);
v[i][j] = 0;
}
int cnt = 0;
for (int i = 0; i != n; ++i)
for (int j = 0; j != m; ++j)
if (a[i][j] && !v[i][j])
{
flag = 1;
dfs(i,j);
cnt += flag;
}
cout << cnt << endl;
return 0;
}