K - 迷宫问题

本文介绍了一个基于广度优先搜索(BFS)算法解决迷宫寻路问题的实现案例。通过使用C++编程语言,该程序能够读取一个5x5的迷宫地图,并找到从起点到终点的路径。利用队列数据结构,BFS算法能够有效地探索迷宫中可达的所有位置。
 1 #include<iostream>
 2 #include<algorithm>
 3 #include<cstdio>
 4 #include<cstring>
 5 using namespace std;
 6 
 7 int Map[6][6],vis[6][6],pre[110];
 8 //pre[]记录每个状态的前一个状态
 9 struct Cam
10 {
11     int x,y;
12 }List[110];
13 
14 int Dire[4][2] = {-1,0,1,0,0,-1,0,1};
15 
16 int Go(int x,int y) //判断是否可走
17 {
18     if(x >= 0 && x < 5 && y >= 0 && y < 5 && Map[x][y] == 0)
19         return 1;
20     return 0;
21 }
22 
23 void Print(int x)
24 {
25     int t;
26     t = pre[x];
27     if(t == 0)
28     {
29         printf("(0, 0)\n");
30         printf("(%d, %d)\n",List[x].x,List[x].y);
31         return ;
32     }
33     else
34         Print(t);
35     printf("(%d, %d)\n",List[x].x,List[x].y);
36 }
37 
38 void BFS()
39 {
40     memset(vis,0,sizeof(vis));
41     int Head = 0,Tail = 1;
42     List[0].x = 0;
43     List[0].y = 0;
44     pre[0] = -1;
45     while(Head < Tail)  //队列
46     {
47         int x = List[Head].x;
48         int y = List[Head].y;
49         if(x == 4 && y == 4)
50         {
51             Print(Head);
52             return ;
53         }
54         for(int i = 0; i < 4; ++i)
55         {
56             int xx = x + Dire[i][0];
57             int yy = y + Dire[i][1];
58             if( !vis[xx][yy] && Go(xx,yy) )
59             {
60                 vis[xx][yy] = 1;
61                 List[Tail].x = xx;
62                 List[Tail].y = yy;
63                 pre[Tail] = Head;
64                 Tail++;
65             }
66         }
67         Head++;
68     }
69     return ;
70 }
71 
72 int main()
73 {
74 
75     for(int i = 0; i < 5; ++i)
76         for(int j = 0; j < 5; ++j)
77             scanf("%d",&Map[i][j]);
78     BFS();
79 
80     return 0;
81 }

 

转载于:https://www.cnblogs.com/ouyang_wsgwz/p/8968388.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值