dfs bfs应用实例,油漆桶应用实例

#include<stdio.h>
struct note
{
	int x;
	int y;
};
int main()
{
	struct note que[2501];
	int head, tail;
	int a[51][51];
	int book[51][51] = { 0 };
	int i, j, k, sum, max = 0, mx, my, n, m, startx, starty, tx, ty;
	int next[4][2] = { {0,1},{1,0},{0,-1},{-1,0} };
	scanf("%d %d %d %d", &n, &m, &startx, &starty);
	for (i = 1; i <= n; i++)
		for (j = 1; j <= m; j++)
			scanf("%d", &a[i][j]);
	head = 1;
	tail = 1;
	que[tail].x = startx;
	que[tail].y = starty;
	tail++;
	book[startx][starty] = 1;
	sum = 1;
	while (head < tail)
	{
		for (k = 0; k <= 3; k++)
		{
			tx = que[head].x + next[k][0];
			ty = que[head].y + next[k][1];
			if (tx<1 || tx>n || ty<1 || ty>m)
				continue;
			if (a[tx][ty] > 0 && book[tx][ty] == 0)
			{
				sum++;
				book[tx][ty] = 1;
				que[tail].x = tx;
				que[tail].y = ty;
				tail++;
			}
		}
		head++;
	}
	printf("%d\n", sum);
	getchar(); getchar();
	return 0;
}

以上为广度优先的应用。具体参见啊哈算法第四章第五节。

#include<stdio.h>
int a[51][51];
int book[51][51], n, m, sum;
void dfs(int x, int y, int color)
{
	int next[4][2] = { {0,1},{1,0},{0,-1},{-1,0} };
	int k, tx, ty;
	a[x][y] = color;
	for (k = 0; k <= 3; k++)
	{
		tx = x + next[k][0];
		ty = y + next[k][1];
		if (tx<1 || tx>n || ty<1 || ty>m)
			continue;
		if (a[tx][ty] > 0 && book[tx][ty] == 0)
		{
			sum++;
			book[tx][ty] = 1;
			dfs(tx, ty, color);
		}
	}
	return;
}
int main()
{
	int i, j, num = 0;
	scanf("%d %d", &n, &m);
	for (int i = 1; i <= n; i++)
		for (j = 1; j <= n; j++)
			scanf("%d", &a[i][j]);
	
	for (i = 1; i <= n; i++)
	{
		for (j = 1; j <= n; j++)
		{
			if (a[i][j] > 0)
			{
				num--;
				book[i][j] = 1;
				dfs(i, j, num);
			}
		}
	}
	for (i = 1; i <= n; i++)
	{
		for (j = 1; j <= m; j++)
		{
			printf("%3d", a[i][j]);
		}
		printf("\n");
	}
	printf("%d个", -num);
	getchar(); getchar();
	return 0;
}

以上是利用dfs写的 并且可以计数小岛个数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值