Contest 8A The Maze runner

Problem A: The Maze runner

Time Limit: 1 Sec   Memory Limit: 128 MB
Submit: 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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值