poj3051

BFS算法详解

bfs

ContractedBlock.gifExpandedBlockStart.gifView Code
#include <iostream>
#include
<cstdlib>
#include
<cstring>
#include
<cstdio>
using namespace std;

#define maxw 85
#define maxh 1005

struct Point
{
int x, y;
Point(
int xx, int yy) :
x(xx), y(yy)
{
}
Point()
{
}
} q[maxw
* maxh];

int w, h;
char map[maxh][maxw];
bool vis[maxh][maxw];
int dir[4][2] =
{
{
1, 0 },
{
0, 1 },
{
-1, 0 },
{
0, -1 } };

bool ok(Point &a)
{
if (a.x < 0 || a.y < 0 || a.x >= h || a.y >= w)
return false;
return !vis[a.x][a.y] && map[a.x][a.y] == '*';
}

int bfs(Point a)
{
int front = 0;
int rear = 0;
int ret = 0;

q[rear
++] = a;
vis[a.x][a.y]
= true;
while (front != rear)
{
Point p
= q[front++];
ret
++;
for (int i = 0; i < 4; i++)
{
Point b(p.x
+ dir[i][0], p.y + dir[i][1]);
if (ok(b))
{
vis[b.x][b.y]
= true;
q[rear
++] = b;
}
}
}
return ret;
}

void work()
{
int ans = 0;
for (int i = 0; i < h; i++)
for (int j = 0; j < w; j++)
if (!vis[i][j] && map[i][j] == '*')
ans
= max(ans, bfs(Point(i, j)));
printf(
"%d\n", ans);
}

int main()
{
//freopen("t.txt", "r", stdin);
scanf("%d%d", &w, &h);
for (int i = 0; i < h; i++)
scanf(
"%s", map[i]);
work();
return 0;
}

转载于:https://www.cnblogs.com/rainydays/archive/2011/09/15/2177714.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值