hdu 4771 Stealing Harry Potter's Precious 状压bfs

17 篇文章 0 订阅

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<queue>

#define N 105

using namespace std;

int key[N][N];
char a[N][N];

int vis[N][N][1<<5];
int dir[4][2] = {
	1, 0, -1, 0, 0, 1, 0, -1
};

struct node {
	int x, y, val, s;
};

int n, m, K;

bool OK( int e, int r )
{
	return (e >= 1 && e <= n && r >= 1 && r <= m);
}

int bfs( node st )
{
	memset(vis, 0, sizeof(vis));
	queue<node> q;
	while( !q.empty() )
		q.pop();
	st.s = 0;
	st.val = key[st.x][st.y];
	vis[st.x][st.y][ key[st.x][st.y] ] = 1;
	q.push(st);
	while( !q.empty() )
	{
		node now = q.front();
		q.pop();
		if ( now.val == (1 << (K+1)) - 2)
			return now.s;
		for ( int i = 0; i < 4; i++ )
		{
			int xx = dir[i][0] + now.x;
			int yy = dir[i][1] + now.y;
			if( OK(xx, yy) && a[xx][yy] != '#' && !vis[xx][yy][now.val] )
			{
				node tmp;
				tmp.x = xx;
				tmp.y = yy;
				tmp.s = now.s + 1;
				tmp.val = now.val | key[xx][yy];
				vis[xx][yy][tmp.val] = 1;
				q.push(tmp);
			}
		}
	}
	return -1;
}

int main()
{
	while(~scanf("%d%d", &n, &m) && (m || n))
	{
		for( int i = 1; i <= n; i++ )
			scanf("%s", a[i] + 1);
		memset( key, 0, sizeof(key) );
		int sx, sy;
		for ( int i = 1; i <= n; i++ )
		{
			for( int j = 1; j <= m; j++ )
			{
				if ( a[i][j] == '@' )
				{
					sx = i;
					sy = j;
					break;
				}
			}
		}
		node st;
		st.x = sx, st.y = sy;
		scanf("%d", &K);
		int e, r;
		for( int i = 1; i <= K; i++ )
		{
			scanf("%d%d", &e, &r);
			key[e][r] |= (1 << i);
		}
		int ans = bfs(st);
		printf("%d\n", ans);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值