1. 程式人生 > >HDU 1072 (基礎BFS)

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;
}