ACM水题-Rescue LK(AC,迷宫问题,DFS求解)

Rescue LK

Time Limit:1000MS  Memory Limit:65536K
Total Submit:83 Accepted:42

Description

ziliang loves LK. But LK was kidnapped by Monster.oyy,and was put in a labyrinth.
After thousands of hard fighting, ziliang finally enter the labyrinth. He must find a way to rescue LK !!! He has a map of the labyrinth, but the puzzle is too complicated, that he need your help.

Input

Input has several case. Each case first give an n and m, that is the height and length of the labyrinth. Followed by the map. In the map, ‘#’ means the wall, ‘Z’ means the position of ziliang, ‘L’ means position of LK. The ‘.’ Means empty cells.
ziliang can only walk on empty cell,and can only go up,down,left,right. And n,m will be less than 50.

Output

If ziliang can reach LK, output “LK has a good life”
Else output “Mission Failed”

Sample Input

5 5
#####
#Z..#
###.#
#..L#
#####

7 7
#######
#Z....#
#####.#
#####.#
#..#..#
#L.####
#######

Sample Output

LK has a good life
Mission Failed

Source

GDUT Monthly 2007.11 by ziliang

 

 

 

/*	------------------------------------------------------------------------------------------
	典型的迷宫问题:通常的做法,就是用栈、DFS这两种做法,不过归根到底其实也是一种,都是回溯而
					已,栈与DFS的区别也就是递归与非递归而已。

    大概想法:用DFS来进行路径探索。每探索一步可行,就设置标志已经走,一直走下去,直到找到终点
			  或者遇到不可行的格子为止。找到终点就返回1,遇到不可行就返回上一层,并重围走过的
			  格子,换一个方向这样。

	状况:AC,0MS
	----------------------------------------------------------------------------------------*/





#include

char chMap[52][52] ;
const int nDir[4][2] = {{1,0},{0,1},{-1,0},{0,-1}} ;   //方向
int m = 0 ;
int n = 0 ;
int zX = 0 ;		//起点的X坐标
int zY = 0 ;		//起点的Y坐标

int DFS(int x,int y) ;

int main(void)
{	
	int i = 0 ;
	int j = 0 ;
	
	while(scanf("%d%d",&n,&m) != EOF)
	{
		getchar() ;
		for(i = 0 ; i < n ; ++i)
		{
			for(j = 0 ; j < m ; ++j)
			{
				scanf("%c",&chMap[i][j]) ;
				if('Z' == chMap[i][j])
				{
					zX = i ;
					zY = j ;
				}
			}
			getchar() ;
		}
		
		if(1 == DFS(zX,zY))
		{
			puts("LK has a good life") ;
		}
		else
		{
			puts("Mission Failed") ;
		}
	}
	return 0 ;
}

int DFS(int x,int y)
{
	int i = 0 ;
	int j = 0 ;
	
	if(x < 0 || y < 0 || x >= n || y >= m)
	{
		return 0 ;
	}

	for(i = 0 ; i < 4 ; ++i)						//换一个方向
	{
		if('L' == chMap[x+nDir[i][0]][y+nDir[i][1]])	
		{
			return 1 ;
		}
		else if('.' == chMap[x+nDir[i][0]][y+nDir[i][1]])		
		{
			chMap[x+nDir[i][0]][y+nDir[i][1]] = '#' ;		//如果格子可行,设置已经
			
			if(1 == DFS(x+nDir[i][0],y+nDir[i][1]))			//设这个方向走下去
			{
				return 1 ;
			}
			chMap[x+nDir[i][0]][y+nDir[i][1]] = '.' ;		//重置原来的状态。
		}
	}	
	return 0 ;
}


 

你可能感兴趣的:(C/C++,数据结构与算法,ACM水题,output,input,less,each,go,up)