fjnu Raiders of the Lost Ark

Raiders of the Lost Ark

Time Limit: 1 Seconds     Memory Limit: 32768 K

Total Submit:535     Accepted:230


Description

In this famous film, renowned archeologist and expert in the occult, Dr. Indiana Jones, is hired by the U.S. Government to find the Ark of the Covenant (聖約櫃), which is believed to still hold the ten commandments (十誡). Unfortunately, agents of Hitler are also after the Ark. Dr. Jones escapes from various close scrapes in a quest that takes him from Nepal to Cairo. Your task is to help him to find the lost Ark of the Covenant in the maze (迷宮) earlier than the enemy.

There are several barriers in the maze, Dr. Jones can bypass these barriers on foot or by jump .He can go on foot in four directions of east, south, west and north to reach a neighboring position. He can also jump cross a cell in the directions of southeast, southwest, northeast and northwest to reach a new position. The following figure shows Dr. Jones’s action where O denotes the original position and × denotes the new possible positions after one action.

Input

The first line of the input is an integer n (0<=n<=20), denoting the number of test cases. The following lines are the data of n test cases. The first line of each test case consists of two integer x and y (0<x<10, 0<y<10). The next x lines describe the maze matrix, which contains x rows and y columns. In the matrix, 'W' denotes the barrier, 'B' denotes the enterable position, ’S’ denotes the starting position, and ‘X’ denotes the position of the ark. There have and only have one ‘S’ and one ‘X’ in a maze matrix.

Output

For each test case, output one line. If there is a solution for the problem, output the number of the least steps to find the Ark. Otherwise output “NO ANSWER”.

Sample Input

3
3 3
SWB
BWB
XBB
5 4
BXWB
BBWS
BBWB
BBWB
BBBB
3 2
WX
WW
WS

 

Sample Output

2
2
NO ANSWER

 

經典的回溯算法題:

Source:

#include<iostream>
using namespace std;
int main()
{
	char a[10][10];
	int n,m,x,y,i,j,sx,sy,x1,y1,x2,y2,min,k[100],flag[10][10]={0};
	int tag[8][2]={-1,0,0,1,1,0,0,-1,-2,2,2,2,2,-2,-2,-2};
	cin>>n;
	while(n--)
	{
		cin>>x>>y;
		for(i=0;i<x;i++)
			for(j=0;j<y;j++)
			{
				cin>>a[i][j];
				if(a[i][j]=='S')
				{
					x1=i;
					y1=j;
				}
			}
         min=32767;
		 i=1;k[0]=0;
		 k[i]=-1;
		 flag[x1][y1]=1;
		 while(i>=1)
		 {
			 while(k[i]<7)
			 {
				 k[i]=k[i]+1;
				 x2=x1+tag[k[i]][0];
				 y2=y1+tag[k[i]][1];
				 if(x2>=0&&x2<x&&y2>=0&&y2<y&&a[x2][y2]!='W'&&i<min)
				 { 
					 if(a[x2][y2]=='X')
					 {					
						 if(i<min)
						    min=i;
					 }
					 else if(flag[x2][y2]==0)
					 {	
						 flag[x2][y2]=1;;
						 x1=x2;
						 y1=y2;
						 i++;						 
						 k[i]=-1;			
					 }					 
				 } 
			 } 				 
			 i--;
			 flag[x1][y1]=0;		
			 x1=x1-tag[k[i]][0];
			 y1=y1-tag[k[i]][1];						 
		 }
		 if(min<32767)
		    cout<<min<<endl;
		 else
			 cout<<"NO ANSWER"<<endl;
	}
   return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章