上一篇
在人工智能和运筹学领域,蚁群算法(Ant Colony Optimization, ACO)是一种模拟自然界蚂蚁觅食行为的智能算法。它被广泛应用于解决旅行商问题(TSP)、网络路由、任务调度等路径优化难题。本教程将带你从零开始,用C++实现一个基础但完整的蚁群算法,即使你是编程小白也能轻松上手!
蚂蚁在寻找食物时会释放一种叫“信息素”的化学物质。其他蚂蚁会感知这种信息素并倾向于选择信息素浓度更高的路径。久而久之,最短路径上的信息素会越来越强,从而引导整个蚁群找到最优路径。
我们将以经典的旅行商问题(TSP)为例:给定若干城市,求访问每个城市一次并返回起点的最短路径。
#include <iostream>#include <vector>#include <cmath>#include <algorithm>#include <random>struct City { double x, y;};// 计算两点间欧氏距离double distance(const City& a, const City& b) { return std::sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));} const int NUM_CITIES = 10; // 城市数量const int NUM_ANTS = 20; // 蚂蚁数量const double ALPHA = 1.0; // 信息素重要程度const double BETA = 2.0; // 启发式因子重要程度const double RHO = 0.5; // 信息素挥发率const int MAX_ITER = 100; // 最大迭代次数std::vector<City> cities(NUM_CITIES);std::vector<std::vector<double>> pheromone(NUM_CITIES, std::vector<double>(NUM_CITIES, 1.0));std::vector<std::vector<double>> heuristic(NUM_CITIES, std::vector<double>(NUM_CITIES));// 初始化启发式矩阵(1 / 距离)for (int i = 0; i < NUM_CITIES; ++i) { for (int j = 0; j < NUM_CITIES; ++j) { if (i != j) { heuristic[i][j] = 1.0 / distance(cities[i], cities[j]); } }} std::vector<int> buildPath(int start, const std::vector<std::vector<double>>& pheromone, const std::vector<std::vector<double>>& heuristic) { std::vector<bool> visited(NUM_CITIES, false); std::vector<int> path; path.push_back(start); visited[start] = true; for (int step = 1; step < NUM_CITIES; ++step) { int current = path.back(); std::vector<double> probs(NUM_CITIES, 0.0); double total = 0.0; // 计算选择每个未访问城市的概率 for (int next = 0; next < NUM_CITIES; ++next) { if (!visited[next]) { probs[next] = std::pow(pheromone[current][next], ALPHA) * std::pow(heuristic[current][next], BETA); total += probs[next]; } } // 轮盘赌选择下一个城市 std::random_device rd; std::mt19937 gen(rd()); std::uniform_real_distribution<> dis(0.0, total); double r = dis(gen); double cum = 0.0; int nextCity = 0; for (int i = 0; i < NUM_CITIES; ++i) { if (!visited[i]) { cum += probs[i]; if (cum >= r) { nextCity = i; break; } } } path.push_back(nextCity); visited[nextCity] = true; } return path;} void updatePheromone(std::vector<std::vector<double>>& pheromone, const std::vector<std::vector<int>>& allPaths, const std::vector<double>& pathLengths) { // 信息素挥发 for (int i = 0; i < NUM_CITIES; ++i) { for (int j = 0; j < NUM_CITIES; ++j) { pheromone[i][j] *= (1.0 - RHO); } } // 蚂蚁释放信息素 for (int ant = 0; ant < NUM_ANTS; ++ant) { double delta = 1.0 / pathLengths[ant]; for (int k = 0; k < NUM_CITIES - 1; ++k) { int from = allPaths[ant][k]; int to = allPaths[ant][k + 1]; pheromone[from][to] += delta; pheromone[to][from] += delta; // 对称TSP } // 回到起点 pheromone[allPaths[ant].back()][allPaths[ant][0]] += delta; pheromone[allPaths[ant][0]][allPaths[ant].back()] += delta; }} int main() { // 随机生成城市坐标(或从文件读取) std::random_device rd; std::mt19937 gen(rd()); std::uniform_real_distribution<> dis(0.0, 100.0); for (auto& city : cities) { city.x = dis(gen); city.y = dis(gen); } double bestLength = std::numeric_limits<double>::max(); std::vector<int> bestPath; for (int iter = 0; iter < MAX_ITER; ++iter) { std::vector<std::vector<int>> allPaths(NUM_ANTS); std::vector<double> pathLengths(NUM_ANTS, 0.0); // 每只蚂蚁构建路径 for (int ant = 0; ant < NUM_ANTS; ++ant) { int start = ant % NUM_CITIES; allPaths[ant] = buildPath(start, pheromone, heuristic); // 计算路径长度 for (int i = 0; i < NUM_CITIES - 1; ++i) { pathLengths[ant] += distance(cities[allPaths[ant][i]], cities[allPaths[ant][i+1]]); } pathLengths[ant] += distance(cities[allPaths[ant].back()], cities[allPaths[ant][0]]); // 更新全局最优解 if (pathLengths[ant] < bestLength) { bestLength = pathLengths[ant]; bestPath = allPaths[ant]; } } updatePheromone(pheromone, allPaths, pathLengths); std::cout << "Iteration " << iter + 1 << ", Best Length: " << bestLength << std::endl; } std::cout << "\nBest Path: "; for (int city : bestPath) std::cout << city << " "; std::cout << "\nBest Length: " << bestLength << std::endl; return 0;} 通过以上步骤,我们用C++实现了一个完整的蚁群算法来解决路径优化问题。这个智能算法的核心在于模拟蚂蚁的信息素通信机制,通过多轮迭代不断强化优质路径。你可以尝试调整参数(如ALPHA、BETA、RHO)或增加城市数量,观察对结果的影响。
希望这篇教程能帮助你理解蚁群算法的基本原理和实现方法。动手试试吧,你会发现智能算法的世界既有趣又实用!
本文由主机测评网于2025-12-08发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://www.vpshk.cn/2025124750.html