1432: 【基础】走出迷宫的最少步数
题目描述
一个迷宫由R行C列格子组成,有的格子里有障碍物,不能走;有的格子是空地,可以走。
给定一个迷宫,求从左上角走到右下角最少需要走多少步(数据保证一定能走到)。只能在水平方向或垂直方向走,不能斜着走。
输入
第一行是两个整数,R和C,代表迷宫的行数和列数。( 1<= R,C <= 40)
接下来是R行,每行C个字符,代表整个迷宫。空地格子用'.'表示,有障碍物的格子用'#'表示。迷宫左上角和右下角都是'.'。
输出
输出从左上角走到右下角至少要经过多少步(即至少要经过多少个空地格子)。计算步数要包括起点和终点。
样例输入复制
5 5
..###
#....
#.#.#
#.#.#
#.#..
样例输出复制
9
#include<bits/stdc++.h>
using namespace std;
int n,m;
int vis[50][50];
char a[50][50];
struct node{
int x,y;
int floor;
struct node * pre=NULL;
};
queue<struct node *> q;
int dx[]={1,0,-1,0};
int dy[]={0,-1,0,1};
int ffloor[50][50];
int main(int argc, char** argv) {
freopen("abc.txt","r",stdin);
cin>>n>>m;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
cin>>a[i][j];
if(a[i][j]=='.'){
vis[i][j]=0;
}else{
vis[i][j]=1;
ffloor[i][j]=0;
}
}
}
vis[0][0]=1;
struct node *head=new struct node;
head->x=0;
head->y=0;
head->floor=1;
ffloor[0][0]=1;
q.push(head);
struct node *tail;
while(!q.empty()){
struct node *h=q.front();
q.pop();
for(int i=0;i<4;i++){
int x=h->x+dx[i];
int y=h->y+dy[i];
if(x>=0&&x<n&&y>=0&&y<m&&vis[x][y]==0){
struct node *t=new node;
t->x=x;
t->y=y;
t->pre=h;
t->floor=h->floor+1;
ffloor[x][y]=t->floor;
q.push(t);
if(t->x==4&&t->y==4){
tail=t;
cout<<"dd"<<endl;
}
vis[x][y]=1;
}
}
}
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
cout<<setw(3)<<ffloor[i][j];
}
cout<<endl;
}
stack<struct node *> s;
while(tail!=NULL){
s.push(tail);
//cout<<tail->x<<","<<tail->y<<endl;
tail=tail->pre;
}
// cout<<(tail->pre->pre)->x<<","<<(tail->pre->pre)->y<<endl;
while(!s.empty()){
cout<<s.top()->x<<", "<<s.top()->y<<endl;
s.pop();
}
return 0;
}