【原创】转载请注明出处 【浙江大学 程序设计专题】

【地图求解器】

本题目要求输入一个迷宫地图,输出从起点到终点的路线。

基本思路是从起点(Sx,Sy)每次枚举该格子上下左右四个方向,直到走到终点(Tx,Ty)。
方法一:如果使用递归方法,则可以使用深度优先搜索算法,但此方法不能保证答案步数最优。
方法二: 如果要求答案步数最少,则使用广度优先搜索算法,但此方法通常不使用递归函数实现。

DFS版代码

 1 #include <stdio.h>
 2 #include <string.h>
 3 
 4 /*Header which contains the output function*/
 5 #include "prnt_route.h"
 6 
 7 int    n,m;
 8 int    visited[1100][1100];
 9 struct PII    from[1100][1100];
10 /*Save the route.*/
11 
12 const int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};
13 
14 char    Map[1100][1100];
15 
16 int    Dfs(const int Sx,const int Sy, const int Tx,const int Ty)
17 {
18     if(Sx==Tx && Sy==Ty) return 1;
19     int i;
20     for(i=0;i<4;++i)/*Search four directions*/
21     {
22         int tx=Sx+dx[i],ty=Sy+dy[i];/*tx,ty refers to the next grid.*/
23         if(tx>=0 && ty>=0 && tx<n && ty<m && 
24             !visited[tx][ty] && Map[tx][ty]!='#')
25         /*check if (tx,ty) is reachable*/
26         {
27             visited[tx][ty]=1;
28             if(Dfs(tx,ty,Tx,Ty))
29             {
30                 /*Route is found.*/
31                 from[tx][ty]=make_pair(Sx,Sy);
32                 return 1;
33             }
34         }
35     }
36     return 0;
37 }
38 
39 int main()
40 {
41     freopen("in.txt","r",stdin);
42     freopen("out.txt","w",stdout);
43     int i,j,Sx,Sy,Tx,Ty;
44     scanf("%d%d",&n,&m);
45     Sx=Sy=1,Tx=n-2,Ty=m-2;
46     for(i=0;i<n;++i) scanf("%s",Map[i]);
47     
48     /*Find the starting and ending points.*/
49     for(i=0;i<n;++i)
50         for(j=0;j<m;++j)
51             if(Map[i][j]=='S') Sx=i,Sy=j;
52             else if(Map[i][j]=='T') Tx=i,Ty=j;
53             
54     /*Dfs will return 1 if a solution is found, 0 otherwise.*/
55     if(Dfs(Sx,Sy,Tx,Ty)) Print_Ans(Sx,Sy,Tx,Ty);
56     else printf("No Solution.\n");
57     return 0;
58 }
View Code

相关文章:

  • 2022-02-06
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-12
  • 2022-03-05
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-01-22
  • 2022-12-23
  • 2022-12-23
  • 2021-04-05
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案