POJ 1376 Robot——C++的BFS解法

本文介绍了一种利用BFS策略求解机器人在迷宫中从起点到终点的最短路径的方法。考虑到方向和步长的选择,通过将方向转化为数字变量,并使用循环找出到转折点的最小步数,最终实现高效路径搜索。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目传送门:http://poj.org/problem?id=1376

洛谷翻译传送门:https://www.luogu.org/problemnew/show/P1126

注:POJ是多组输入,洛谷是单组输入。

『解题思路』


采用BFS策略求从起点到终点的最短路,题目有点坑,输入的是方格坐标,但机器人移动的是点,应该注意。因为还有方向问题,故而首先将方向转化为数字变量,便于计算旋转的步数。

north —— 0;east —— 1;south —— 2;west —— 3;

因为步长有三种选择1,2,3,所以应该使用循环找出到转折点最小的步数,然后将转折点存入队列中,进行下一次搜索。

『代码』


#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <queue>
#define For(a,b,c,d) for(register int a=b;a<=c;a+=d)
using namespace std;
int my[ 4 ] = { 0 , 1 , 0 , -1 } , mx[ 4 ] = { -1 , 0 , 1 , 0 } ;
int n , m , maze[ 55 ][ 55 ] ;
bool vis[ 20000 ] ;
//压缩 
int fun( int a , int b , int c ) {
	return c * 2700 + a * 51 + b ;
}
struct Node {
	int x , y ;
	int f ;
	int mov ;
} ;
queue<Node> que ;
 bool zq( int x , int y ) {
	if( maze[ x ][ y ] || maze[ x + 1 ][ y ] || maze[ x ][ y + 1 ] || maze[ x + 1 ][ y + 1 ] )
		return 1 ;
	return 0 ;
}
 void bfs() {
 	string str;
	int x , y , tx , ty , f , d , mov , lx , ly ;
	char c[10];
	scanf("%d %d %d %d %s" , &x , &y , &tx , &ty , c );
	str = c;
	if(str == "north")//将方向转换为数字 
		f = 0 ;
	else if(str == "east")
		f = 1;
	else if(str == "south")
		f = 2;
	else if(str == "west")
		f = 3;
	Node temp ;
	temp.x = x , temp.y = y , temp.f = f , temp.mov = 0 ;
	que.push( temp ) ;
	while( !que.empty() ) {
		temp = que.front() ;
		que.pop() ;
		x = temp.x , y = temp.y , f = temp.f , d = fun( x , y , f ) , mov = temp.mov ;
		if( x == tx && y == ty ) {
			printf("%d\n",mov) ;
			return ;
		}
		if( vis[ d ] )
			continue ;
		vis[ d ] = 1 ;//将访问过的点标志下来 
		temp.mov ++ ;
		temp.f = ( f + 4 - 1 ) % 4 ;
		que.push( temp ) ;
		temp.f = ( f + 4 + 1 ) % 4 ;
		que.push( temp ) ;
		temp.f = f ;
		For( i , 1 , 3 , 1 ) {//找出最小的步数 
			lx = x + mx[ f ] * i , ly = y + my[ f ] * i ;
			if( lx <= 0 || ly <= 0 || lx >= n || ly >= m || zq( lx , ly ) )//判断边界 
				break ;
			temp.x = lx ;
			temp.y = ly ;
			que.push( temp ) ;
		}
	}
	printf("-1\n");
}
int main() {
	while(scanf("%d %d" , &n , &m )) {
		memset(vis,0,sizeof(vis)); 
		if(n == 0 && m == 0)
			break;
		For( i , 1 , n , 1 ) {
			For( j , 1 , m , 1 ) {
				scanf("%d", &maze[ i ][ j ] );
			}
		}
		while(!que.empty()){
			que.pop();
		}
		bfs() ;
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值