礦工冒險記

現在你控制的人物在一個N×M的場地中,左上角的方格爲 (0, 0),右下角爲 (N – 1, M – 1),你一開始的位置在 (SX, SY),你家的位置則在 (EX, EY)。身爲一個礦工,你身上早就有了好幾組鐵和鑽石,所以你正匆忙地趕回家裏。但是有某些格子被設下了陷阱,如果走到上面就會粉身碎骨,立刻 Game Over。你當然不想 Game Over,所以你要避開這些格子。

假設每單位時間能向上、下、左、右移動一個格子,請你計算一下最短回家的時間。

輸入格式

一個整數 T,表示有多少組測試數據。

接下來的 T 組測試數據,每組測試數據第一行是兩個正整數 NM (1 <= N, M <= 10),表示場地大小。

第二行有一個正整數 P (0 <= P <= N × M),表示有多少個方格被設下了陷阱。

接下來的 P 行,每行是兩個整數 XY,表示陷阱座標。

最後一行是四個整數 SXSYEXEY,表示起始位置和家的位置。

注意,行走不能超出地圖邊界。

輸出格式

對於每組輸入數據,輸出一行一個數字,表示最少需要的回家時間。假如有不可能完成任務的情況,輸出 -1。

樣例輸入

1
3 3
2
1 1
1 2
0 0 2 2

樣例輸出

4

本題使用廣度優先搜索算法,因爲相鄰兩點的長度都一樣,所以先到終點的就是最短路徑。
下面是本人的代碼:
#include<stdio.h>
#include<queue>
#include<string.h>
using namespace std;

struct Point
{
	int x;
	int y;
	Point(int a,int b){x=a;y=b;}
};

int a[10][10];
int N, M, P;
int SX, SY, EX, EY;
int xi[4]={-1,  1,  0, 0}; //搜索方向:上,下,左,右
int yi[4]={  0,  0, -1, 1};
void print()
{
	int i,j;
	for(i=0;i<M;i++)
	{
		for(j=0;j<N;j++)
			printf("%d ",a[i][j]);
		printf("\n");
	}
}

int BFS()
{
	queue<Point> q;
	q.push(Point(SX, SY));
	while(!q.empty())
	{
		Point p=q.front();
		if(p.x==EX && p.y==EY)
			return a[EX][EY];
		q.pop();
		int tempX, tempY, i,  j;
		for(i=0;i<4;i++)
		{
			tempX=p.x;
			tempY=p.y;
			tempX=tempX+xi[i];
			tempY=tempY+yi[i];
			if(tempX>=0 && tempY>=0 && tempX<M && tempY<N && a[tempX][tempY]==0) //沒有越界、不是陷阱、未被訪問過
			{
				q.push(Point(tempX, tempY));
				a[tempX][tempY]=a[p.x][p.y]+1; //更新位置(tempX, tempY)到(SX,SY)的距離
				if(tempX==EX && tempY==EY)
					return a[tempX][tempY];
				//a[tempX][tempY]=1;
			}	
		}
	}
	return -1;
}
int main()
{
	int T;
	scanf("%d",&T);
	while(T--)
	{
		int i, j;
		memset(a,0,sizeof(a)); //初始化值爲0
		int x,y;
		scanf("%d%d%d",&M,&N,&P);
		for(i=0;i<P;i++)
		{
			scanf("%d%d",&x,&y);
			a[x][y]=-1; //將有陷阱的地方的值,置爲-1
		}
		scanf("%d%d%d%d",&SX, &SY, &EX, &EY);
		int dis=BFS();
		printf("%d\n",dis);
		//print();
	}

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章