贪婪最佳优先搜索算法(Greedy Best-First Search Algorithm)在C++中的实现

千晨小哥_2942

千晨小哥_2942

2023-09-13

3507人浏览

转载

贪婪最佳优先搜索算法(greedy best-first search algorithm)在c++中的实现

计算机科学中良好的问题解决很大程度上依赖于高效的算法,例如贪婪最佳优先搜索(GBFS)。 GBFS 已经确立了作为寻路或优化问题的最佳解决方法的可信度。因此,我们在本文中深入讨论 GBFS,同时探索其使用 C++ 的实现方法。

语法

void greedyBestFirstSearch(Graph graph, Node startNode, Node goalNode);

算法

贪心最佳优先搜索算法旨在找到图中从给定起始节点到目标节点的路径。以下是该算法的一般步骤 -

  • 初始化一个空的优先级队列。

  • 将起始节点放入优先级队列。

  • 创建一个空集来跟踪访问过的节点。

  • 当优先级队列不为空时 -

  • 将优先级最高的节点从队列中出列。

  • 如果出队的节点是目标节点,则算法终止,并找到路径。

  • 否则,将出队节点标记为已访问。

  • 将出队节点的所有未访问的邻居节点放入优先级队列中。

  • 如果优先级队列在到达目标节点之前变空,则不存在路径。

方法一:基于欧氏距离的启发式函数

示例

#include <iostream>
#include <queue>
#include <cmath>
#include <vector>
#include <unordered_set>

using namespace std;

// Structure to represent a node in the graph
struct Node {
   int x, y; // Coordinates of the node
   int cost; // Cost to reach this node
};

// Euclidean distance heuristic function
double euclideanDistance(int x1, int y1, int x2, int y2) {
   return sqrt(pow((x1 - x2), 2) + pow((y1 - y2), 2));
}

// Custom comparison function for nodes in the priority queue
struct NodeCompare {
   bool operator()(const Node& node1, const Node& node2) const {
      return node1.cost > node2.cost;
   }
};

// Greedy Best-First Search function
void greedyBestFirstSearch(vector<vector>>& graph, Node start, Node goal) {
   int rows = graph.size();
   int cols = graph[0].size();

   // Priority queue for nodes to be explored
   priority_queue<node vector>, NodeCompare> pq;

   // Visited nodes set
   unordered_set<int> visited;

   // Add the start node to the priority queue
   pq.push(start);

   while (!pq.empty()) {
      // Get the node with the lowest cost
      Node current = pq.top();
      pq.pop();

      // Check if the current node is the goal node
      if (current.x == goal.x && current.y == goal.y) {
         cout = 0 && newX = 0 && newY > graph = {
      {3, 5, 1, 2},
      {1, 3, 2, 4},
      {5, 2, 6, 7},
      {4, 3, 1, 2}
   };

   Node start;
   start.x = 0; // Starting x-coordinate
   start.y = 0; // Starting y-coordinate
   start.cost = 0; // Cost to reach the starting node

   Node goal;
   goal.x = 3; // Goal x-coordinate
   goal.y = 3; // Goal y-coordinate

   // Run Greedy Best-First Search algorithm
   greedyBestFirstSearch(graph, start, goal);

   return 0;
}
</int></node></vector></unordered_set></vector></cmath></queue></iostream>

输出

Goal node reached!

说明

这段代码包含两个关键元素。首先,它包含 Graph 类的定义,该类表示使用邻接表的图结构。

其次,它引入了 CompareEuclideanDistance - 一个自定义比较器,用于通过使用欧几里德距离公式估计节点与目标节点的距离来评估节点。

greedyBestFirstSearch 函数实现贪婪最佳优先搜索算法。它使用优先级队列根据节点的启发值来存储节点。

该算法首先将起始节点放入优先级队列中。

在每次迭代中,它将最高优先级的节点出队并检查它是否是目标节点。

如果找到目标节点,则会显示“路径已找到!”消息被打印。否则,算法将出队的节点标记为已访问,并将其未访问的相邻节点放入队列。

如果优先级队列变空而没有找到目标节点,则会显示“不存在路径!”消息已打印。

main函数通过创建图、定义起始节点和目标节点以及调用greedyBestFirstSearch函数演示了算法的用法。

方法2:基于曼哈顿距离的启发式函数

我们解决此问题的策略需要使用依赖于曼哈顿距离概念的启发式函数。这种距离度量有时称为出租车距离,涉及将节点之间的水平和垂直距离相加。

示例

#include <iostream>
#include <queue>
#include <cmath>
#include <vector>
#include <unordered_set>

using namespace std;

// Structure to represent a node in the graph
struct Node {
   int x, y; // Coordinates of the node
   int cost; // Cost to reach this node
};

// Manhattan distance heuristic function
int manhattanDistance(int x1, int y1, int x2, int y2) {
   return abs(x1 - x2) + abs(y1 - y2);
}

// Custom comparison function for nodes in the priority queue
struct NodeCompare {
   bool operator()(const Node& node1, const Node& node2) const {
      return node1.cost > node2.cost;
   }
};

// Greedy Best-First Search function
void greedyBestFirstSearch(vector<vector>>& graph, Node start, Node goal) {
   int rows = graph.size();
   int cols = graph[0].size();

   // Priority queue for nodes to be explored
   priority_queue<node vector>, NodeCompare> pq;

   // Visited nodes set
   unordered_set<int> visited;

   // Add the start node to the priority queue
   pq.push(start);

   while (!pq.empty()) {
      // Get the node with the lowest cost
      Node current = pq.top();
      pq.pop();

      // Check if the current node is the goal node
      if (current.x == goal.x && current.y == goal.y) {
         cout = 0 && newX = 0 && newY > graph = {
      {3, 5, 1, 2},
      {1, 3, 2, 4},
      {5, 2, 6, 7},
      {4, 3, 1, 2}
   };

   Node start;
   start.x = 0; // Starting x-coordinate
   start.y = 0; // Starting y-coordinate
   start.cost = 0; // Cost to reach the starting node

   Node goal;
   goal.x = 3; // Goal x-coordinate
   goal.y = 3; // Goal y-coordinate

   // Run Greedy Best-First Search algorithm
   greedyBestFirstSearch(graph, start, goal);

   return 0;
}
</int></node></vector></unordered_set></vector></cmath></queue></iostream>

输出

Goal node reached!

说明

该代码遵循与方法 1 类似的结构,但使用自定义比较器 CompareManhattanDistance,该比较器使用曼哈顿距离公式根据到目标节点的估计距离来比较节点。

greedyBestFirstSearch 函数使用曼哈顿距离启发式实现贪婪最佳优先搜索算法。

main函数演示了算法的使用,创建一个图,定义起始节点和目标节点,并调用greedyBestFirstSearch函数。

结论

在本文中,我们探讨了贪婪最佳优先搜索算法及其在 C++ 中的实现。通过采用这些方法,程序员可以有效地找到图中的路径并解决优化问题。启发式函数的选择,例如欧氏距离或曼哈顿距离,可以显着影响算法在不同场景下的性能。

C++免费学习笔记(深入):立即使用
在学习笔记中,你将探索 C++ 的入门与实战技巧!

c++速学教程(入门到精通)
c++速学教程(入门到精通)

c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

相关标签:

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

更多
页面置换算法
页面置换算法

页面置换算法是操作系统中用来决定在内存中哪些页面应该被换出以便为新的页面提供空间的算法。本专题为大家提供页面置换算法的相关文章,大家可以免费体验。

2023.08.14

7236

4

Go-Zero API开发使用教程
Go-Zero API开发使用教程

本专题聚焦Go-Zero的API开发,拆解.api描述文件的语法结构、路由与分组定义、参数绑定与校验规则,说明统一响应体、JWT鉴权、跨域与接口文档生成的落地方式,并给出网关聚合与接口测试的实践建议。

2026.11.12

140

15

Go-Zero安装与goctl环境配置教程
Go-Zero安装与goctl环境配置教程

本专题围绕Go-Zero的安装与工具链配置展开,讲清Go版本要求、goctl安装方式、代理镜像、protoc依赖与环境变量设置,说明多版本共存、升级回退与CI流水线安装的做法,并整理安装阶段的常见报错与验证步骤。

2026.11.12

100

15

Go-Zero零基础入门教程
Go-Zero零基础入门教程

本专题整理Go-Zero的入门知识,从框架定位、环境准备到跑通第一个API服务,讲清目录分层、配置加载、日志与中间件的基本用法,并对比Gin、Kratos的差异,帮助Go开发者建立整体认知,判断它是否适合当前项目。

2026.11.12

80

15

Postman身份认证怎么配置
Postman身份认证怎么配置

本专题从实际API接口调试场景出发,讲解Postman身份认证的完整配置流程,包括常见认证协议介绍、授权参数设置、访问令牌填写、OAuth 2.0授权及认证失败排查,帮助用户正确完成接口授权与访问验证。

2026.11.06

160

12

Postman请求头Headers怎么设置
Postman请求头Headers怎么设置

围绕Postman HTTP请求头配置展开,讲解Headers选项的具体使用方式,包括Key和Value参数填写、请求头信息添加、常见Header字段设置及请求头修改方法,帮助用户解决接口调试过程中遇到的请求头配置问题。

2026.11.06

140

13

Postman接口请求发送教程
Postman接口请求发送教程

详细介绍Postman接口请求的创建与发送方法,涵盖GET和POST请求、URL配置、请求参数、Headers请求头、Body请求体设置以及响应结果查看,帮助用户掌握Postman接口请求的完整操作流程。

2026.11.06

120

10

DBeaver怎么导入数据
DBeaver怎么导入数据

DBeaver数据导入专题,整理Excel、CSV、SQL、TXT等常见文件的数据导入方法,涵盖目标数据库选择、数据表创建、字段映射、数据类型设置及导入参数配置等操作,帮助用户将本地文件中的数据写入数据库,并了解批量导入、重复数据处理和导入失败等常见问题的解决方法。

2026.11.05

100

12

DBeaver安全防护教程大全
DBeaver安全防护教程大全

DBeaver安全防护专题,围绕数据库连接安全、账号密码保护和访问权限管理展开,整理SSL/TLS加密连接、SSH隧道、数据库凭据保存及证书验证等配置方法,同时介绍敏感信息保护、远程连接风险和高权限账号使用等注意事项,帮助用户提高数据库日常管理的安全性。

2026.11.05

100

12

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
热门推荐
/
最新课程
phpStudy极速入门视频教程
phpStudy极速入门视频教程

共6课时 | 54.7万人学习

独孤九贱(4)_PHP视频教程
独孤九贱(4)_PHP视频教程

共89课时 | 134.3万人学习