杭电OJ 1198(C++)

#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
const int MAXN = 55;

struct farm //农田
{
	int x; //mp数组中的x坐标
	int y; //mp数组中的y坐标
	int kind; //农田类型
}now, nex;

int M, N; //输入
char mp[MAXN][MAXN]; //输入的地图
int vis[MAXN][MAXN]; //每一块农田的访问情况
int fx[4] = { -1,0,1,0 }; //x轴移动方向
int fy[4] = { 0,-1,0,1 }; //y轴移动方向
int dir[11][4] = { {1,1,0,0},{1,0,0,1},{0,1,1,0},{0,0,1,1},
				   {1,0,1,0},{0,1,0,1},{1,1,0,1},{1,1,1,0},
				   {0,1,1,1},{1,0,1,1},{1,1,1,1} }; //每块农田的4个方向是否有水管

//广搜,将能从mp[i][j]起始,水管连接的所有点vis置为1
void bfs(int x, int y)
{
	now.x = x;
	now.y = y;
	now.kind = mp[x][y] - 'A';
	vis[x][y] = 1;
	queue<farm> s;
	s.push(now);
	while (!s.empty())
	{
		now = s.front();
		s.pop();
		for (int i = 0; i < 4; i++) //搜索4个方向,将能连接的农田vis置1
		{
			nex.x = now.x + fx[i];
			nex.y = now.y + fy[i];
			nex.kind = mp[nex.x][nex.y] - 'A';
			if (nex.x >= 0 && nex.x < M && nex.y >= 0 && nex.y < N && vis[nex.x][nex.y] == 0)
			{
				if (dir[now.kind][i] == 1 && dir[nex.kind][(i + 2) % 4] == 1)
				{
					vis[nex.x][nex.y] = 1;
					s.push(nex);
				}
			}
		}
	}
}

int main()
{
	while (cin >> M >> N)
	{
		if (M < 0 || N < 0)
			break;
		memset(vis, 0, sizeof(vis));
		for (int i = 0; i < M; i++)
		{
			cin >> mp[i];
		}
		int total = 0; //需要水源的数量
		for (int i = 0; i < M; i++)
		{
			for (int j = 0; j < N; j++)
			{
				if (vis[i][j] == 0)
				{
					++total;
					bfs(i, j);
				}
			}
		}
		cout << total << endl;
	}
}
发布了138 篇原创文章 · 获赞 1 · 访问量 7013

猜你喜欢

转载自blog.csdn.net/Intelligence1028/article/details/104593658