您的位置:首页 > 其它

poj2386(简单dfs)

2014-12-06 11:36 363 查看
就是求图中有多少个水洼。对图进行dfs遍历,并把是水洼的地方全部标记。然后从下一个是水哇的地方再进行dfs。

#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
int graph[105][105];
int sum;
bool vis[105][105];
int dx[] = {-1, -1, -1,  0, 0,  1, 1, 1};
int dy[] = {-1,  0,  1, -1, 1, -1, 0 ,1};
int row, col;

bool check(int x, int y)
{
if( x >= 0 && x < row && y >= 0 && y < col)
return true;
return false;
}

void dfs(int x, int y)
{
int ix, iy;
for(int i = 0; i < 8; i++)
{
ix = x + dx[i];
iy = y + dy[i];
if(!vis[ix][iy] && check(ix, iy) && graph[ix][iy] == 1)
{
vis[ix][iy] = true;
dfs(ix, iy);
}
}
}
int main()
{
//freopen("in.txt", "r", stdin);
cin >> row >> col;
getchar();
memset(vis, false, sizeof(vis));

char c;
for(int i = 0; i < row; i ++)
{
for(int j = 0; j < col; j++)
{
c = getchar();
graph[i][j] = (c == '.') ? 0 : 1;
}
getchar();
}
sum = 0;

for(int i  = 0; i < row; i ++)
{
for(int j = 0; j < col; j++)
{
if(graph[i][j] == 1 && vis[i][j] == false)
{
sum++;
vis[i][j] = true;
dfs(i, j);
}
}
}

cout << sum << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: