SWUST OJ 4: Maze Problem(C语言实现)

题目描述

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即返回,可以提高效率

传送门

SWUST OJ 4: Maze Problem

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值