您的位置:首页 > 其它

Flood fill种子填充(DFS求连通快)

2015-03-27 21:04 357 查看
Flood fill算法是从一个区域中提取若干个连通的点与其他相邻区域区分开(或分别染成不同颜色)的经典算法。因为其思路类似洪水从一个区域扩散到所有能到达的区域而得名。算法分为四路算法(不考虑对角线方向的节点)和八路算法(考虑对角线方向的节点)。



例题:HDOJ 1241 Oil Deposits

#include<cstdio>
#include<cstring>
int n, m;
char map[102][102];
int mark[102][102];
int dis[8][2] = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 }, { 1, -1 }, { -1, 1 }, { 1, 1 }, { -1, -1 } };
void bfs(int x, int y, int sum)
{
mark[x][y] = 1;
int tx, ty,i;
for (i = 0; i < 8; i++)
{
tx = x + dis[i][0];
ty = y + dis[i][1];
if (tx >= 0 && tx < n&&ty >= 0 && ty < m&&!mark[tx][ty]&&map[tx][ty]=='@')
bfs(tx, ty, sum);
}
}
int main()
{
int i, j, ans;
while (scanf("%d %d", &n, &m), n + m)
{
memset(mark, 0, sizeof(mark));
ans = 0;
for (i = 0; i < n; i++)
scanf("%s", map[i]);
for (i = 0; i < n;i++)
for (j = 0; j < m; j++)
{
if (map[i][j] == '@'&&!mark[i][j])
bfs(i, j, ++ans);
}
printf("%d\n", ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: