一维坐标的移动(BFS)

 

#include<iostream>
#include<queue>
using namespace std;
int n,a,b;
struct node
{
	int x;
	int d;
	node(int xx,int dd)
	{
		x=xx;
		d=dd;
	}
};
int v[1010];//判断是否走过 
queue<node>q;
void bfs(int m,int step)
{
	q.push(node(m,step));
	v[m]=1;
	while(!q.empty() )
	{
		if(q.front().x==b)
		{
			cout<<q.front().d;
			break;
		}
		
		if(q.front().x+1<n&&!v[q.front().x+1])
		{
			v[q.front().x+1]=1;
			q.push(node(q.front().x+1,q.front().d+1)); 
		}
		if(q.front().x-1>=0&&!v[q.front().x-1])
		{
			v[q.front().x-1]=1;
			q.push(node(q.front().x-1,q.front().d+1)); 
		}
		if(q.front().x*2<n&&!v[q.front().x*2])
		{
			v[q.front().x*2]=1;
			q.push(node(q.front().x*2,q.front().d+1)); 
		}
		q.pop() ;
	}
}
int main()
{
	cin>>n>>a>>b;
	bfs(a,0);
	
	return 0;
} 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是Python实现代码: ```python from collections import deque # 定义坐标类 class Coordinate: def __init__(self, x, y): self.x = x self.y = y # 定义BFS函数 def bfs(start, end, maze): queue = deque() # 记录起点到每个点的最短距离 distance = [[-1] * len(maze[0]) for _ in range(len(maze))] distance[start.x][start.y] = 0 queue.append(start) while queue: cur = queue.popleft() # 找到终点,返回最短路径长度 if cur.x == end.x and cur.y == end.y: return distance[cur.x][cur.y] # 四个方向进行搜索 for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]: new_x, new_y = cur.x + dx, cur.y + dy # 如果新坐标越界或者是墙壁或者已经被搜索过,直接跳过 if not (0 <= new_x < len(maze) and 0 <= new_y < len(maze[0]) and maze[new_x][new_y] == '.' and distance[new_x][new_y] == -1): continue # 更新最短距离并加入队列 distance[new_x][new_y] = distance[cur.x][cur.y] + 1 queue.append(Coordinate(new_x, new_y)) # 没有找到终点,返回-1 return -1 # 读入输入 start_x, start_y, end_x, end_y = map(int, input().split()) maze = [] for i in range(10): maze.append(input()) # 计算乌龟到终点的距离 turtle_distance = abs(end_x - start_x) + abs(end_y - start_y) # 计算兔子到终点的最短路径长度 start = Coordinate(start_x, start_y) end = Coordinate(end_x, end_y) rabbit_distance = bfs(start, end, maze) # 计算兔子比乌龟多走的距离 extra_distance = rabbit_distance - turtle_distance # 输出结果 print('%.2f' % extra_distance) ``` 注意,以上代码中用到了坐标类`Coordinate`和队列`deque`。`Coordinate`类用于表示二维坐标,`deque`则是Python标准库中的双端队列,可以高效地实现队列的操作。在BFS中,我们需要使用队列来保存待搜索的坐标

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值