貪婪最佳優先搜尋演算法(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<int>>& 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<Node>, 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 << "Goal node reached!" << endl; return; } // Mark the current node as visited int nodeId = current.x * cols + current.y; visited.insert(nodeId); // Explore the neighboring nodes int dx[] = {-1, 1, 0, 0}; // Possible x-direction movements int dy[] = {0, 0, -1, 1}; // Possible y-direction movements for (int i = 0; i < 4; i++) { int newX = current.x + dx[i]; int newY = current.y + dy[i]; // Check if the neighboring node is within the graph boundaries if (newX >= 0 && newX < rows && newY >= 0 && newY < cols) { // Calculate the heuristic value for the neighboring node double heuristicValue = euclideanDistance(newX, newY, goal.x, goal.y); // Check if the neighboring node has not been visited if (visited.find(newX * cols + newY) == visited.end()) { // Create a new node for the neighboring position Node neighbor; neighbor.x = newX; neighbor.y = newY; neighbor.cost = current.cost + graph[newX][newY]; // Add the neighboring node to the priority queue pq.push(neighbor); } } } } cout << "Goal node not reachable!" << endl; } int main() { // Example graph represented as a 2D vector vector<vector<int>> 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; }
輸出
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<int>>& 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<Node>, 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 << "Goal node reached!" << endl; return; } // Mark the current node as visited int nodeId = current.x * cols + current.y; visited.insert(nodeId); // Explore the neighboring nodes int dx[] = {-1, 1, 0, 0}; // Possible x-direction movements int dy[] = {0, 0, -1, 1}; // Possible y-direction movements for (int i = 0; i < 4; i++) { int newX = current.x + dx[i]; int newY = current.y + dy[i]; // Check if the neighboring node is within the graph boundaries if (newX >= 0 && newX < rows && newY >= 0 && newY < cols) { // Calculate the heuristic value for the neighboring node int heuristicValue = manhattanDistance(newX, newY, goal.x, goal.y); // Check if the neighboring node has not been visited if (visited.find(newX * cols + newY) == visited.end()) { // Create a new node for the neighboring position Node neighbor; neighbor.x = newX; neighbor.y = newY; neighbor.cost = current.cost + graph[newX][newY]; // Add the neighboring node to the priority queue pq.push(neighbor); } } } } cout << "Goal node not reachable!" << endl; } int main() { // Example graph represented as a 2D vector vector<vector<int>> 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; }
輸出
Goal node reached!
說明
程式碼遵循與方法 1 類似的結構,但使用自訂比較器 CompareManhattanDistance,該比較器使用曼哈頓距離公式根據到目標節點的估計距離來比較節點。
greedyBestFirstSearch 函數使用曼哈頓距離啟發式實現貪婪最佳優先搜尋演算法。
main函數示範了演算法的使用,建立一個圖,定義起始節點和目標節點,並呼叫greedyBestFirstSearch函數。
結論
在本文中,我們探討了貪婪最佳優先搜尋演算法及其在 C 中的實作。透過採用這些方法,程式設計師可以有效地找到圖中的路徑並解決最佳化問題。啟發式函數的選擇,例如歐氏距離或曼哈頓距離,可以顯著影響演算法在不同場景下的表現。
以上是貪婪最佳優先搜尋演算法(Greedy Best-First Search Algorithm)在C++中的實現的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

C語言數據結構:樹和圖的數據表示與操作樹是一個層次結構的數據結構由節點組成,每個節點包含一個數據元素和指向其子節點的指針二叉樹是一種特殊類型的樹,其中每個節點最多有兩個子節點數據表示structTreeNode{intdata;structTreeNode*left;structTreeNode*right;};操作創建樹遍歷樹(先序、中序、後序)搜索樹插入節點刪除節點圖是一個集合的數據結構,其中的元素是頂點,它們通過邊連接在一起邊可以是帶權或無權的數據表示鄰

文件操作難題的真相:文件打開失敗:權限不足、路徑錯誤、文件被佔用。數據寫入失敗:緩衝區已滿、文件不可寫、磁盤空間不足。其他常見問題:文件遍歷緩慢、文本文件編碼不正確、二進製文件讀取錯誤。

C語言函數是代碼模塊化和程序搭建的基礎。它們由聲明(函數頭)和定義(函數體)組成。 C語言默認使用值傳遞參數,但也可使用地址傳遞修改外部變量。函數可以有返回值或無返回值,返回值類型必須與聲明一致。函數命名應清晰易懂,使用駝峰或下劃線命名法。遵循單一職責原則,保持函數簡潔性,以提高可維護性和可讀性。

C語言函數名定義包括:返回值類型、函數名、參數列表和函數體。函數名應清晰、簡潔、統一風格,避免與關鍵字衝突。函數名具有作用域,可在聲明後使用。函數指針允許將函數作為參數傳遞或賦值。常見錯誤包括命名衝突、參數類型不匹配和未聲明的函數。性能優化重點在函數設計和實現上,而清晰、易讀的代碼至關重要。

C35 的計算本質上是組合數學,代表從 5 個元素中選擇 3 個的組合數,其計算公式為 C53 = 5! / (3! * 2!),可通過循環避免直接計算階乘以提高效率和避免溢出。另外,理解組合的本質和掌握高效的計算方法對於解決概率統計、密碼學、算法設計等領域的許多問題至關重要。

C語言函數是可重複利用的代碼塊,它接收輸入,執行操作,返回結果,可將代碼模塊化提高可複用性,降低複雜度。函數內部機制包含參數傳遞、函數執行、返回值,整個過程涉及優化如函數內聯。編寫好的函數遵循單一職責原則、參數數量少、命名規範、錯誤處理。指針與函數結合能實現更強大的功能,如修改外部變量值。函數指針將函數作為參數傳遞或存儲地址,用於實現動態調用函數。理解函數特性和技巧是編寫高效、可維護、易理解的C語言程序的關鍵。

算法是解決問題的指令集,其執行速度和內存佔用各不相同。編程中,許多算法都基於數據搜索和排序。本文將介紹幾種數據檢索和排序算法。線性搜索假設有一個數組[20,500,10,5,100,1,50],需要查找數字50。線性搜索算法會逐個檢查數組中的每個元素,直到找到目標值或遍歷完整個數組。算法流程圖如下:線性搜索的偽代碼如下:檢查每個元素:如果找到目標值:返回true返回falseC語言實現:#include#includeintmain(void){i

C語言多線程編程指南:創建線程:使用pthread_create()函數,指定線程ID、屬性和線程函數。線程同步:通過互斥鎖、信號量和條件變量防止數據競爭。實戰案例:使用多線程計算斐波那契數,將任務分配給多個線程並同步結果。疑難解答:解決程序崩潰、線程停止響應和性能瓶頸等問題。
