迷宫-BFD-C++

求迷宫中入口和出口距离

给定一个n*m数组,数组中存放字符。*代表墙壁,. 代表空地,S代表起点,T代表终点。每次只能向上下左右四个方向移动一个位置。求S到T的要走多少步。

思路:BFS。从起点S开始计数遍历层数,每经过一层计数加1。

注意点:参考

求矩阵中块数
代码:

#include<bits\stdc++.h>
using namespace std;
const int N = 100;
const int dx[] = {0,0,-1,1};
const int dy[] = {-1,1,0,0};
struct Matrix{
	char position;
	bool visited;
}matrix[N][N];
struct Node{
	int x;
	int y;
	int step;//step表示从S到该位置最少多少步
};
Node start,end;//起点和终点
int row,col;//迷宫行数列数
void BFS(){
	queue<Node> q;
	q.push(start);
	while(!q.empty()){
		Node top = q.front();
		matrix[top.x][top.y].visited = true; 
		if(matrix[top.x][top.y].position == 'T'){
			end.x = top.x;
			end.y = top.y;
			end.step = top.step;
			return;
		}
		q.pop();
		for(int i = 0;i < 4;i ++){
			int new_x = top.x + dx[i];
			int new_y = top.y + dy[i];
			if(new_x >= 0 && new_y >= 0 && new_x < row && new_y < col){
				if(matrix[new_x][new_y].position != '*' && matrix[new_x][new_y].visited == false){
					Node temp;
					temp.x = new_x;
					temp.y = new_y;
					temp.step = top.step + 1;
					q.push(temp);
				}
			}
		}
	}
}
int main(){
	cin>>row>>col;
	for(int i = 0;i < row;i ++){
		for(int j = 0;j < col;j ++){
			cin>>matrix[i][j].position;
			matrix[i][j].visited = false;
			if(matrix[i][j].position == 'S'){
				start.x = i;
				start.y = j;
				start.step = 0;
			}
		}
	} 
	BFS();
	cout<<end.step<<endl;
	
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值