万圣节后的早晨

// by BNU_LZM
#include<cstdio>
#include<queue>
#include<vector>
#include<cstring>
#include<algorithm>
using namespace std;

char map[20][20];
int s[4], t[4], d[300][300][300];

int dx[] = {0, 0, 0, 1, -1};
int dy[] = {0, 1, -1, 0, 0};

vector<int> a[300];

int ID(int x, int y, int z)
{
	return (x<<16) | (y<<8) | z;
}

bool pd(int x, int nx, int y, int ny)
{
	if((x == ny && y == nx) || (nx == ny)) return true;
	else return false;
}

int bfs()
{
	queue<int> q;
	q.push(ID(s[0], s[1], s[2]));
	memset(d, -1, sizeof(d));
	d[s[0]][s[1]][s[2]] = 0;
	while(!q.empty())
	{
		int u = q.front(); q.pop();
		int x = (u>>16) & 0xff, y = (u>>8) & 0xff, z = u & 0xff;
		if(x == t[0] && y == t[1] && z == t[2]) return d[x][y][z];
		for(int i = 0; i < a[x].size(); i++)
		{
			int nx = a[x][i];
			for(int j = 0; j < a[y].size(); j++)
			{
				int ny = a[y][j];
				if(pd(x, nx, y, ny)) continue;
				for(int k = 0; k < a[z].size(); k++)
				{
					int nz = a[z][k];
					if(pd(x, nx, z, nz)) continue;
					if(pd(y, ny, z, nz)) continue;
					if(d[nx][ny][nz] > -1) continue;
					d[nx][ny][nz] = d[x][y][z]+1;
					q,push(ID(nx, ny, nz));
				}
			}
		}
	}
	return -1;
}

int main()
{
	int h, w, n;
	int x[300], y[300], id[20][20];
	scanf("%d%d%d", &h, &w, &n);
	for(int i = 0; i < h; i++)
		fgets(map[i], 20, stdin);
	int cnt = 0;
	for(int i = 0; i < h; i++)
		for(int j = 0; j < w; j++)
		{
			if(map[i][j] != '#')
			{
				x[cnt] = i; y[cnt] = j;
				if(islower(map[i][j]))
				{
					s[map[i][j]-'a'] = cnt;
				}
				if(isupper(map[i][j]))
				{
					t[map[i][j]-'A'] = cnt;
				}
				id[i][j] = cnt;
				cnt++;
			}
		}
	for(int i = 0; i < cnt; i++)
	{
		for(int j = 0; j < 5; j++)
		{
			int nx = x[i]+dx[j], ny = y[i]+dy[j];
			if(nx < 0 || nx >= w || ny < 0 || ny >= h) continue;
			if(map[nx][ny] != '#')
			{
				a[i].push_back(id[nx][ny]);
			}
		}
	}
	if(n <= 2) { s[2] = t[2] = cnt; a[cnt].push_back(cnt); cnt++; }
	if(n <= 1) { s[1] = t[1] = cnt; a[cnt].push_back(cnt); cnt++; }
	printf("%d\n", bfs());
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值