UVA 1600 Patrol Robot

#include <cstdio>
#include <algorithm>
#include <vector>
#include <cstring>

using namespace std;
typedef pair<int,int> int_pair;
typedef pair<int_pair,int> status;


int vis[25][25][20];
int G[25][25];
int n,m,k;

const int walk_r[4]={0,-1,0,1};
const int walk_c[4]={1,0,-1,0};

bool inside(int_pair x)
{
	if(x.first>0&&x.first<=m&&x.second>0&&x.second<=n)
		return true;
	else
		return false;
}

int bfs()
{
	int cnt=0;
	vector<status> Q1;
	vector<status> Q2;
	int_pair a(1,1);
	status b(a,k);
	Q1.push_back(b);
	while(!Q1.empty())
	{
		for(int i=0;i<Q1.size();i++)
		{
			status u=Q1[i];
			int_pair from=u.first;
			vis[from.first][from.second][u.second]=1;
			for(int j=0;j<4;j++)
			{
				int r1=from.first+walk_r[j];
				int c1=from.second+walk_c[j];
				int_pair to(r1,c1);
				if(inside(to))
				{
					if(G[r1][c1]==1&&u.second>=1&&!vis[r1][c1][u.second-1])
					{
						if(r1==m&&c1==n)
						{
							return ++cnt;
						}
						status v(to,u.second-1);
						Q2.push_back(v);
					}
					else if(G[r1][c1]==0&&!vis[r1][c1][k])
					{
						if(r1==m&&c1==n)
						{
							return ++cnt;
						}
						status v(to,k);
						Q2.push_back(v);
					}
				}
			}
		}
        Q1=Q2;
        cnt++;
        Q2.clear();
	}
	return -1;
}

int main()
{
	int T;
	scanf("%d", &T);
	while(T--)
	{
		memset(G,0,sizeof(G));
		memset(vis,0,sizeof(vis));
		scanf("%d %d", &m, &n);
		scanf("%d", &k);
		for(int i=1;i<=m;i++)
		{
			for(int j=1;j<=n;j++)
			{
				scanf("%d", &G[i][j]);
			}
		}
		int step=bfs();
		printf("%d\n", step);
	}
	return 0;
}

思路比較簡單,做一次bfs。但是標記是否訪問過圖中某點的vis數組需要增加一個維度,表示機器人訪問到該點時可以繼續經過的有障礙物的方格的個數。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章