HDU 1072 (基础BFS)

这个题 还有有点烦的……应该是我菜的缘故……

其实刚开始一点问题都没有 就寻常的BFS过去 开始觉得他烦的时候 是我发现这道题他不能标记……

对他可以回头走 甚至是必须回头走(例如案例二)

总之我的代码中还可以看到标记数组的痕迹

回头走了 一旦有两个4离得近了 小于6步那么 就会死循环……

所以就应该标记4 这个4不能让他来回走

然后 我这个题我还用了优先队列 其实完全没有必要 就算要优先也是要以步数为最优先

其实我本来是用时间优先的 但是很明显不可以啊

3 3
1 1 4
1 1 1
1 3 1
 

这样的反例比比皆是 把自己蠢哭……

#include <iostream>
#include <string>
#include <cstring>
#include <sstream>
#include <algorithm>
#include <vector>
#include <queue>
#include <map>
#include <cmath>
using namespace std;

struct node
{
	int x, y;
	int time;
	int step;
	friend bool operator < (node a, node b)
	{
		return a.step > b.step;
	}
};

int n, m;
int mm[15][15];
//int vis[15][15];
int mov[][2] = { 0,1,1,0,0,-1,-1,0 };
node tt;

bool bfs()
{
	priority_queue<node>q;
	q.push(tt);
	while (q.size())
	{
		tt = q.top(); q.pop();
		for (int i = 0; i < 4; i++)
		{
			int xx = tt.x + mov[i][0];
			int yy = tt.y + mov[i][1];
			if (xx < 0 || yy < 0 || xx >= n || yy >= m || mm[xx][yy]==0)
				continue;
			//vis[xx][yy] = 1;
			node a;
			a.time=tt.time + 1;
			a.step=tt.step + 1;
			if (a.time >= 6)continue;
			if (mm[xx][yy] == 4) { a.time = 0; mm[xx][yy] = 0; }
			if (mm[xx][yy] == 3)return true;
			a.x = xx;
			a.y = yy;
			q.push(a);
		}
	}
	return false;
}

int main()
{
	int t;
	cin >> t;
	while (t--)
	{
		//memset(vis, 0, sizeof(vis));
		cin >> n >> m;
		for (int i = 0; i < n; i++)
		{
			for (int j = 0; j < m; j++)
			{
				cin >> mm[i][j]; 
				if (mm[i][j] == 2)
				{
					tt.x = i;
					tt.y = j;
					tt.time = 0;
					tt.step = 0;
				}
			}
		}
		if (bfs())
		{
			cout << tt.step + 1 << endl;
		}
		else
			cout << "-1" << endl;
	}
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42191950/article/details/82953023