soj 1135. 飞越原野

bfs,

strcut Status { int x, y, rest, step; }; 入队列,进行扩展直到到达目的地,vis[][][]标记剩下某能量达到某位置是否有过

代码:

#include <cstring>
#include <queue>
#include <cstdio>
using namespace std;
#define N 102
int r, c, d, ans;
char data[N][N];
bool vis[N][N][N];
struct Item
{
	int x, y, rest, step;
	Item() {}
	Item(int _x, int _y, int _r, int _s): x(_x), y (_y), rest(_r), step(_s) {}
	bool legal() {return x>0 && x<=r && y>0 && y<=c && data[x][y]=='P' && !vis[x][y][rest];}
	bool destinate() {return x==r && y==c;}
	void visit() {vis[x][y][rest] = true;}
};
int dir[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};
int bfs()
{
	if (r == 1 && c == 1) return 0;
	vis[1][1][d] = true;
	queue <Item> Q;
	Q.push(Item(1,1,d,0));
	Item cur, nxt;
	while (!Q.empty())
	{
		cur = Q.front();
		Q.pop();
		for (int i = 0; i < 4; ++ i)
		{
			nxt = Item(cur.x+dir[i][0], cur.y+dir[i][1], cur.rest, cur.step+1);
			if (nxt.legal())
			{
				nxt.visit();
				Q.push(nxt);
				if (nxt.destinate()) return nxt.step;
			}
			for (int j = 2; j <= cur.rest; ++ j)
			{
				nxt = Item(cur.x+j*dir[i][0], cur.y+j*dir[i][1], cur.rest-j, cur.step+1);
				if (nxt.legal())
				{
					nxt.visit();
					Q.push(nxt);
					if (nxt.destinate()) return nxt.step;
				}
			}
		}
	}
	return -1;
}
int main()
{
	while (~scanf("%d %d %d", &r, &c, &d))
	{
		memset(vis, false, sizeof(vis));
		for (int i = 1; i <= r; ++ i)
			scanf("%s", data[i]+1);
		ans = bfs();
		if (ans == -1) printf("impossible\n");
		else printf("%d\n", ans);
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值