Acwing 844.裸迷宫

给定一个n*m的二维整数数组,用来表示一个迷宫,数组中只包含0或1,其中0表示可以走的路,1表示不可通过的墙壁。

最初,有一个人位于左上角(1, 1)处,已知该人每次可以向上、下、左、右任意一个方向移动一个位置。

请问,该人从左上角移动至右下角(n, m)处,至少需要移动多少次。

数据保证(1, 1)处和(n, m)处的数字为0,且一定至少存在一条通路。

输入格式

第一行包含两个整数n和m。

接下来n行,每行包含m个整数(0或1),表示完整的二维数组迷宫。

输出格式

输出一个整数,表示从左上角移动至右下角的最少移动次数。

数据范围

1n,m1001≤n,m≤100

输入样例:

5 5
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0

输出样例:

8
思路:

 

 换句人话------->初始化队列,While队列不为空,每次把队头(auto t = q.front()然后q.pop(或者 auto t = q[h++]))拿出来,然后拓展完成后t = (q.push({x,y}或者q[++t]={x,y});

 
 1 #include<iostream>
 2 #include<cstring>
 3 
 4 using namespace std;
 5 
 6 typedef pair<int,int> PII;//存储状态
 7 const int N = 110;
 8 PII q[N*N];
 9 int d[N][N];//存距离
10 int g[N][N];//存地图
11 int r,c;//行列
12 
13 int bfs(){
14     int tt = 0,hh = 0;//定义队头,和队尾
15     q[0] = {0,0};//初始化队列状态
16     
17     memset(d,-1,sizeof d);//将全部的地图初始化为-1,如果是0的话就是我们走过的单元
18     
19     d[0][0] = 0;//第一个初始化为0也就是走过的
20     
21     int dx[4] = {-1,0,1,0},dy[4]={0,1,0,-1};//根据上右下左,表示移动的方向
22     
23     while(hh <= tt){//当队头不为空
24         auto t = q[hh ++];//去头
25         for(int i = 0;i < 4;i++){//操作的四个方向
26             int x = t.first+dx[i],y = t.second+dy[i];//定义移动方向的坐标
27             if(x >= 0 && x < r && y >= 0 && y < c && g[x][y] == 0 && d  [x][y] == -1){
28                 d[x][y] = d[t.first][t.second] + 1;// 状态拓展----难点就是d[t.first][t.second]是d[x][y]的前一个位置的最大距离emmmmm卡了我好久
29                 q[++tt] = {x,y};//状态转移
30             }
31         }
32     }
33     return d[r - 1][c - 1];
34 }
35 
36 int main(){
37     scanf("%d%d",&r,&c);    
38     for(int i = 0;i < r;i++)
39         for(int j = 0;j < c;j++)
40             scanf("%d",&g[i][j]);
41     
42     printf("%d",bfs());
43     
44 }

 

 1 #include<iostream>
 2 #include<cstring>
 3 #include<queue>//加上队列函数
 4 using namespace std;
 5 
 6 typedef pair<int,int> PII;//存储状态
 7 const int N = 110;
 8 int d[N][N];//存距离
 9 int g[N][N];//存地图
10 int r,c;//行列
11 int bfs(){
12     queue<PII> q;
13     q.push({0,0});//初始化队列状态
14     
15     memset(d,-1,sizeof d);//将全部的地图初始化为-1,如果是0的话就是我们走过的单元
16     
17     d[0][0] = 0;//第一个初始化为0也就是走过的
18     
19     int dx[4] = {-1,0,1,0},dy[4]={0,1,0,-1};//根据上右下左,表示移动的方向
20     
21     while(q.size()){//当队头不为空
22     //去头
23         auto t = q.front();
24         q.pop();
25         for(int i = 0;i < 4;i++){//操作的四个方向
26             int x = t.first+dx[i],y = t.second+dy[i];//定义移动方向的坐标
27             if(x >= 0 && x < r && y >= 0 && y < c && g[x][y] == 0 && d[x][y] == -1){
28                 d[x][y] = d[t.first][t.second] + 1;// 状态拓展
29                 q.push({x,y});//状态转移
30             }
31         }
32     }
33     return d[r - 1][c - 1];
34 }
35 
36 int main(){
37     scanf("%d%d",&r,&c);    
38     for(int i = 0;i < r;i++)
39         for(int j = 0;j < c;j++)
40             scanf("%d",&g[i][j]);
41     
42     printf("%d",bfs());
43     
44 }

 

posted @ 2019-09-28 21:03  香草味羊扒饭  阅读(139)  评论(0编辑  收藏  举报