HDU 2560 拓展 dfs解决矩阵中的分组问题
作者:互联网
给一个01的矩阵,相邻的1可以分成1组组成一个建筑物,问有多少个建筑物
dfs:
```cpp
#include<stdio.h>
#include<iostream>
#include<algorithm>
#define MAXN_ROW 100
#define MAXN_COL 100
using namespace std;
int dx[4] = { 0,0,-1,1 };
int dy[4] = { -1,1,0,0 };
int map[MAXN_ROW][MAXN_COL];
bool vis[MAXN_ROW][MAXN_COL];
void dfs(int i, int j) //dfs访问第i行第j列的点
{
vis[i][j] = 1;
for (int k = 0; k < 4; k++)
{
int newx = i + dx[k];
int newy = j + dy[k];
if (map[newx][newy] != 0 && vis[newx][newy]==0)
{
dfs(newx, newy);
}
}
}
int main()
{
int m, n;
int cnt = 0;
scanf("%d%d", &m, &n);
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
scanf("%d", *(map + i) + j);
}
}
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
if (map[i][j] == 1)
{
if (vis[i][j] == 0)
{
dfs(i, j);
cnt++;
}
}
}
}
printf("%d\n", cnt);
return 0;
}
标签:map,HDU,vis,int,2560,dfs,++,MAXN 来源: https://blog.csdn.net/qq_45992231/article/details/118913833