(算法练习)——BFS(广度优先搜索)【出迷宫】

《算法笔记》P280
这一题值得珍藏!!

#include <stdio.h>
#include <string.h>
#include <queue>
using namespace std;
const int maxn = 100;
struct node{
	int x,y;//位置{x,y} 
	int step;//step为从起点S到大该位置的最少步数(层数) 
}S,T,Node;//分别为起点、终点、临时节点 

int n,m;
char maze[maxn][maxn];
bool inq[maxn][maxn] = {false};//记录位置{x,y}是否已入过队 
int X[4] = {0,0,1,-1};//增量数组 
int Y[4] = {1,-1,0,0};

bool test(int x,int y){//检测这个位置是否有效 
	if(x >= n || x <0 || y >=m || y <0) return false;
	if(maze[x][y] == '*') return false;
	if(inq[x][y] == true) return false;
	return true;
}

int BFS(){
	queue<node> q;
	q.push(S);
	while(!q.empty()){
		node top = q.front();//取出队首元素 
		q.pop();//队首元素出队 
		if(top.x == T.x && top.y == T.y){//若就是终点,直接返回最少步数 
			return top.step;
		}
		for(int i = 0;i <4;i++){//循环4次,得到4个相邻位置 
			int newX = top.x + X[i];
			int newY = top.y + Y[i];
			if(test(newX,newY)){//新位置有效,启动Node(临时节点) 
				Node.x = newX,Node.y = newY;
				Node.step = top.step + 1;
				q.push(Node);
				inq[newX][newY] = true;//设置位置(newX,newY)已入过队 
			}
		}
	}
	return -1;//无法到达终点T时返回-1 
}

int main(){
	scanf("%d%d",&n,&m);//行数、列数 
	for(int i = 0;i <n;i++){
		getchar();
		for(int j = 0;j <m;j++){
			maze[i][j] = getchar();
		}
		maze[i][m+1] = '\0';
	}
	scanf("%d%d%d%d",&S.x,&S.y,&T.x,&T.y);//起点与终点的坐标 
	S.step = 0;//初始化起点层数为0 
	printf("%d\n",BFS());
	return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值