Uva1600——Patrol Robot

这题:找最短路径,只是可以跨越障碍,不能连续跨越K个障碍。

可以通过BFS做。


一开始我没有用vis数组,是在输入的矩阵中操作的,结果一直WR,不明白,为毛加了vis就可以,同样是标记的,自己还是有待提高。


下面AC代码:

#include <iostream>
#include <queue>
#include <cstring>
using namespace std;

struct node
{
	int x, y, count, sum;    //xy为坐标,count为走了多少步,sum为连续跨越几个障碍了。
};

int xy[4][2] = {{0, -1}, {1, 0}, {0, 1}, {-1, 0}};
int num[25][25];
int n, m, k;

bool vis[25][25][25];

int bfs(int x1, int y1, int x2, int y2)
{
	node no;
	no.x = x1; no.y = y1;
	no.count = 0;
/*	if(num[x1][y1] == 1)    //起点是1,看作已经跨越障碍了,不需要障碍数 + 1.
		no.sum = 1;
	else*/
		no.sum = 0;
	queue<node> Q;
	Q.push(no);
	memset(vis, 0, sizeof(vis));
	vis[0][0][0] = true;
//	num[x1][y1] = -1;
	while(!Q.empty())
	{
		node nod = Q.front();
		Q.pop();
		if(nod.x == x2 && nod.y == y2)
			return nod.count;
		
		for(int i = 0; i < 4; i++)
		{
			int x = nod.x + xy[i][0], y = nod.y + xy[i][1], z = nod.count, s = nod.sum;
			if(!(x >= 0 && x < n && y >= 0 && y < m))
				continue;
			if(num[x][y])
				s++;
			else
				s = 0;
			if(s > k || vis[x][y][s])
				continue;
			vis[x][y][s] = true;
			no.x = x; no.y = y;
			no.count = z + 1;
			no.sum = s;
			Q.push(no);
		}
	}
	return -1;
}

int main()
{
	freopen("1.txt", "r", stdin);
	int t;
	cin >> t;
	while(t--)
	{
		cin >> n >> m;
		cin >> k;
		for(int i = 0; i < n; i++)
			for(int j = 0; j < m; j++)
				cin >> num[i][j];
		int x1 = 0, y1 = 0, x2 = n - 1, y2 = m - 1;
		cout << bfs(x1, y1, x2, y2) << endl;
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值