题目描述
Given a maze, find a shortest path from start to goal.
什么意思呢,就是给你一个迷宫,让你找到一条从起点到终点的最短路径,用搜索就可以搞定
输入
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:
For a character in the map:
‘S’ : start cell ‘E’ : goal cell ‘-’ : empty cell ‘#’ : obstacle cell
no two start cell exists. no two goal cell exists.
输出
For each test case print one line containing shortest path. If there exists no path from start to goal, print -1.
样例输入
1
5 5
S-###
-----
##---
E#---
---##
样例输出
9
AC代码
#include<stdio.h>
int d[4][2]={{0,1},{1,0},{0,-1},{-1,0}};//设定前进方向
int n,m,step,min=9999;//n,m表示 maze 大小,min存储最短路径,初始化为一个很大的值(这里初始化为9999)
char map[100][100],book[100][100];//,map数组储存地图,book数组标记是否走过
void dfs(int x,int y,int step);
int main()
{
int No;
scanf(" %d",&No);//输入测试组数
while(No--)//多组输入
{
min=9999;book[100][100]={0};
int starty,startx;
scanf("%d %d",&n,&m);
for(int i=0;i<n;++i)
for(int j=0;j<m;++j)
{
scanf(" %c",&map[i][j]);
if(map[i][j]=='S')//用starty和startx存储起点在迷宫中的位置
{
starty=i;
startx=j;
}
}
book[starty][startx]=1;
dfs(startx,starty,0);
if(min==9999)//表示没有找到最短路径
printf("-1\n",min);
else//有最短路径
printf("%d\n",min);
}
return 0;
}
void dfs(int x,int y,int step)
{
if(map[y][x]=='#')//遇见障碍
return;
if(y>n||y<0||x>m||x<0)//超越边境
return;
if(map[y][x]=='E')//找到终点
{
min=min<step?min:step;
return;
}
for(int u=0;u<4;++u)//依次尝试下一个点
{
if(book[y+d[u][0]][x+d[u][1]]==0)//判断是否搜索过
{
book[y+d[u][0]][x+d[u][1]]=1;
dfs(x+d[u][1],y+d[u][0],step+1);
book[y+d[u][0]][x+d[u][1]]=0;//这一步很重要,置为0后才可重新搜索
}
}
return;
}
PS:可在DFS函数前部分加上一条终止条件判断,比较min和step大小的语句,当step>=min即返回,可以提高效率