bfs实现迷宫路径最小

You are provided a maze(迷宫), and you need to program to find the least steps to walk from the start to the end.And you can only walk in four directions:up, down,left, right.

There will only be 5 kinds of characters in the maze.The meaning of each is as followed.

"#" is for rock, which you can not walk through.

"S" is for start.

"E" is for end.

"." is for road.

"!" is for magma(岩浆),which you can not walk through.

Input

n,m represent the maze is a nxm maze.(n rows, m columnsm,0 <n,m <= 21).

Then is the maze.

e.g.

5 5

#####

#S..#

#.!.#

#.#E#

#####

 

Output

You need to give the least steps to walk from start to the end.If it doesn't exist, then output -1.

e.g.(for the example in input)

4

使用bfs,用queue来实现:

#include<iostream>
#include<string.h>
#include<queue>
using namespace std;
int bfs();
    char maze[22][22];
    int visit[22][22];
    int s[4][2]= {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
    int n, m, start1, start2, end1, end2;
    struct node{
		int x, y, step;
		node(int x1, int y1, int step1): x(x1), y(y1), step(step1) {}
	};
int main() {
	cin>> n>> m;
	memset(visit, 0, sizeof(visit));
	for (int i= 0; i< n; i++) {
		for (int j= 0; j< m; j++) {
			cin>> maze[i][j];
			if (maze[i][j]== 'S') {
				start1= i, start2= j;
			}
			if (maze[i][j]== 'E') {
				end1= i, end2= j;
			}
		}
	}
	cout<< bfs();
}
int bfs() {
	node f(start1, start2, 0);
	queue<node> q;
	while (!q.empty()) q.pop();
	q.push(f);
	while (!q.empty()) {
		f= q.front();
		q.pop();
		if (f.x== end1&&f.y== end2) {
			return f.step;
		}
		visit[f.x][f.y]= 1;
		for (int i= 0; i< 4; i++) {
			int x= f.x+ s[i][0];
			int y= f.y+ s[i][1];
			if (x== end1&&y== end2) {
			return f.step+ 1;
		}
			if (x>= 0&&x< n&&y>= 0&&y< m&&maze[x][y]== '.'&&visit[x][y]== 0) {
				visit[x][y]= 1;
				node next(x, y, f.step+ 1);
				q.push(next);
			}
		}
	}
	return -1;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值