搜索BFS算法

bfs(广度搜索法)

1.首先确定搜索方向(4.6.8个方向)

2.确定搜索的起点与终点    /*多起点的情况还需要多学习*/

3.可通过队列已确定步数


例题1:Dungeon Maste (三维地牢,题目略)

之前wa原因,没有考虑边界情况

ac代码:


#include <cstdio>
#include <iostream>
#include <queue>
#include <string>
using namespace std ;

int ax[6] = {1,-1,0,0,0,0} ;
int ay[6] = {0,0,1,-1,0,0} ;
int az[6] = {0,0,0,0,1,-1} ;
char ch[40][40][40] ;
int starx , stary ,starz , endx , endy , endz ;
int bfs ( int ll , int rr , int hh )
{
	int a , b, c , d ,e, f , g ;
	queue <int> qx ; queue <int> qy ; queue <int> qz ; queue <int> qt ;
	qx.push( starx ) ; qy.push( stary ) ; qz.push( starz ) ; qt.push(0) ;  
	//将初始起点推入队列 
	while( !qx.empty() )
	{
		int t=0 ;
		a = qx.front() ; b = qy.front() ; c = qz.front() ; g = qt.front() ; 
		qx.pop() ; qy.pop() ; qz.pop() ; qt.pop() ;
		for( int i=0 ; i < 6 ; i++ )
		{
			d = a + ax[i] ;
			e = b + ay[i] ;
			f = c + az[i] ;
			if( d < 0  || e < 0 || f < 0 )
			continue ;
			if( d==ll || e==rr || f==hh )
			continue ;                         //确定边界 
			if( ch[d][e][f] == '.' )
			{
				qx.push( d ) ; qy.push( e ) ; qz.push( f ) ; qt.push(g+1) ;
				ch[d][e][f] = '#' ;
			}
			if( ch[d][e][f] == 'E' ) return ( g+1 ) ;   //返回步数 
		}
	}
	return -1 ;
}

int main()
{
	int l , r , h ;
	while( ~scanf("%d%d%d" , &l , &r ,&h) )
	{
		if( l==0 && r==0 && h==0 ) break ;
		getchar() ;
		int i , j , k ;
		for( i=0 ; i<l ; i++ )
		   for( j=0 ; j<r ; j++ )
		    {
		    	scanf("%s" , &ch[i][j] ) ;
		    	for( k=0 ; k<h ; k++ )
		    	{
		    		if( ch[i][j][k] == 'S' )                 //寻找起点与终点 
		         	{
		    	     	starx = i ; stary = j ; starz = k;
			    	}
			     	if( ch[i][j][k] == 'E' ) 
		        	{
		         		endx = i ; endy = j ; endz = k ;
				    }
			  	}
			}
	    int can = bfs(l,r,h) ;
	    if( can == -1 ) printf("Trapped!\n") ;
	    else printf("Escaped in %d minute(s).\n" , can ) ;
	}
   	return 0 ;
}

代码总结:可用结构体将坐标和步数同一减少队列的数量。

对bfs反思:会基础使用队列进行bfs搜索,但是还需多考虑多起点情况。不清楚的地方是bfs回溯保存路径并输出路径;



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值