UVa 572 油田(DFS求连通块)

时间:2021-05-29 21:42:07

https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=513

终于开始接触图了,恩,开始接触DFS了,这道题就是求连通分量,比较简单。

 #include<iostream>
#include<cstring>
using namespace std; int m, n; //记录连通块的数量
char a[][];
int b[][]; void DFS(int i, int j, int count)
{
if (i < || i >= m || j < || j >= n) return; //在递归时出界的情况
if(b[i][j]> || a[i][j]!='@') return;
b[i][j] = count;
for (int p = -; p <= ; p++)
{
for (int q = -; q <= ; q++)
{
if (p != ||q != ) DFS(i + p, j + q, count);
}
}
} int main()
{
while (cin >> m >> n && m && n)
{
for (int i = ; i < m; i++)
scanf("%s", &a[i]);
int count = ;
memset(b, , sizeof(b));
for (int i = ; i < m; i++)
{
for (int j = ; j < n; j++)
{
if (b[i][j] == && a[i][j]=='@') DFS(i, j, ++count);
}
}
cout << count << endl;
}
return ;
}

2016-12-03  07:49:56