Problem A: The Maze runner
Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 468 Solved: 256
[ Submit][ Status][ Web Board]
Description
Given a maze, find a shortest path from start to exit.
Input
Input consists serveral test cases.
First line of the input contains number of test case T.
For each test case the first line contains two integers N , M ( 1 <= N, M <= 100 ).
Each of the following N lines contain M characters. Each character means a cell of the map.
Here is the definition for chracter.
Constraint:
A map consists of 4 kinds of characters:
‘S’ means the start point;
‘E’ means the exit point;
‘.’ means the opened-block that you can pass;
‘#’ means the closed-block that you cannot pass;
Requirements:
It is ONLY allowed to move by one step vertically or horizontally( up, down , left or right) to the next block;
You MUST NOT get out of the map;
Return -1 if given arguments can not satisfy the above requirements or you cannot find a way from ‘S’ to ‘E’.
Output
For each test case print one line containing shortest path. If there exists no path from start to goal, print -1.
Sample Input
4
4 4
####
#S##
#.E#
####
6 5
#####
#.S.#
#.#.#
#..##
##.E#
#####
4 4
####
#S##
##E#
####
6 8
########
#.....##
#.##...#
#..#.#.#
#S#..E.#
########
Sample Output
2
6
-1
10
HINT
#include<stdio.h>
char maze[20][20];
int x,y;
int min=-1;
int move[4][2]={{0,1},{1,0},{-1,0},{0,-1}};
void DFS(int a,int b,int step)
{
int i,tx,ty;
for(i=0;i<4;i++){
tx=a+move[i][0];
ty=b+move[i][1];
if(tx<0||tx>=x||ty<0||ty>=y||maze[tx][ty]=='#')
continue;
if(maze[tx][ty]=='E'&&step+1<min){
min=step+1;
return;
}
if(maze[tx][ty]!='E')
maze[tx][ty]='#';
DFS(tx,ty,step+1);
if(maze[tx][ty]!='E')
maze[tx][ty]='-';
}
}
int main()
{
int T;
scanf("%d",&T);
while(T-->0){
int i,j;
scanf("%d%d",&x,&y);
for(i=0;i<x;i++)
scanf("%s",maze[i]);
for(i=0;i<x;i++)
for(j=0;j<y;j++)
if(maze[i][j]=='S'){
min=99;
maze[i][j]='#';
DFS(i,j,0);
break;
}
if(min==99)
min=-1;
printf("%d\n",min);
}
return 0;
}