百练#3752走迷宫

描述
一个迷宫由R行C列格子组成,有的格子里有障碍物,不能走;有的格子是空地,可以走。
给定一个迷宫,求从左上角走到右下角最少需要走多少步(数据保证一定能走到)。只能在水平方向或垂直方向走,不能斜着走。
输入
第一行是两个整数,R和C,代表迷宫的长和宽。( 1<= R,C <= 40)
接下来是R行,每行C个字符,代表整个迷宫。
空地格子用’.‘表示,有障碍物的格子用’#‘表示。
迷宫左上角和右下角都是’.’。
输出
输出从左上角走到右下角至少要经过多少步(即至少要经过多少个空地格子)。计算步数要包括起点和终点。
样例输入

5 5
…###
#…
#.#.#
#.#.#
#.#…

样例输出

9

#include<iostream>
#include<queue>
#include<utility>
#include<cstring>
#define INF -1
using namespace std;
char mg[45][45];
int f[4][2] = {{0,-1},{-1,0},{0,1},{1,0}};
typedef pair<int,int> P;
int main(){
	int r,c,i,j,x,y;
	int d[45][45];
	scanf("%d%d",&r,&c);
	for(i = 0;i < r; ++i){
		getchar();
		for(j = 0;j < c; ++j){
			scanf("%c",&mg[i][j]);
		} 
	}
	memset(d,INF,sizeof(d));
	queue<P> q;
	q.push(P(0,0));
	d[0][0] = 1;
	while(!q.empty()){
		P p = q.front();
		q.pop();
		if(p.first == r - 1 && p.second == c - 1)
			break;
		for(i = 0;i < 4; ++i){
			x = p.first + f[i][0];
			y = p.second + f[i][1];
			if(x >= 0 && x < r && y >= 0 && y < c && (mg[x][y] == '.' && d[x][y] == INF)){
				q.push(P(x,y));
				d[x][y] = d[p.first][p.second] + 1;
			}
		}
	}
	printf("%d",d[r - 1][c - 1]);
	return 0;
}

bfs求最短路径
主要是使用c++容器 queue 还有pair结构。

发布了53 篇原创文章 · 获赞 0 · 访问量 725

猜你喜欢

转载自blog.csdn.net/weixin_38894974/article/details/104375211
今日推荐