hdu1198

hdu1198

Farm Irrigation

0x00 Tags

并查集

0x01 题目简介

0x02 代码

#include<bits/stdc++.h>

using namespace std;

const int N = 510;

const int directions[11][4] = {
	{1,1,0,0},{0,1,1,0},{1,0,0,1},{0,0,1,1},
	{0,1,0,1},{1,0,1,0},{1,1,1,0},{1,1,0,1},
	{1,0,1,1},{0,1,1,1},{1,1,1,1}
};


int n, m, num, ans;

int root[N * N + 1];
char f[N][N];


void Init()
{
	for (int i = 1; i < n * m; i++)
	{
		root[i] = i;
	}
}


int Find(int x)
{
	return x == root[x] ? x : Find(root[x]);
}


void Union(int x1, int y1, int x2, int y2, int dir)
{
	if (x2 > n || y2 > m) return;

	bool flag = false;

	int t1, t2;
	t1 = f[x1][y1] - 'A';
	t2 = f[x2][y2] - 'A';

	if (dir == 1)
	{
		if (directions[t1][3] && directions[t2][1]) flag = true;
	}
	else
	{
		if (directions[t1][2] && directions[t2][0]) flag = true;
	}

	if (flag)
	{
		int a = Find((x1 - 1) * m + y1), b = Find((x2 - 1) * m + y2);

		if (a != b)
		{
			root[b] = a;
			ans--;
		}
	}
}


int main()
{

	while (scanf("%d%d", &n, &m) != EOF)
	{
		if (n == -1 && m == -1) break;

		Init();

		ans = n * m;

		for (int i = 1; i <= n; i++)
		{
			scanf("%s", f[i] + 1);
		}

		for (int i = 1; i <= n; i++)
		{
			for (int j = 1; j <= m; j++)
			{
				Union(i, j, i + 1, j, 1);
				Union(i, j, i, j + 1, 0);
			}
		}

		printf("%d\n", ans);
	}


	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值