Heuristic Panelusuran minangka pendekatan algoritmik sing kuat sing digunakake kanggo nemokake solusi ing ruang masalah sing rumit kanthi nggawe keputusan sing adhedhasar heuristik utawa aturan jempol. Iku utamané migunani nalika panelusuran exhaustive ora praktis amarga papan panelusuran gedhe.
Cara Kerjane
- Heuristic Evaluasi: Algoritma ngevaluasi saben negara ing ruang masalah nggunakake heuristic fungsi. Fungsi iki ngira "promisingness" saben negara ing babagan cedhak karo negara tujuan.
- Strategi Panelusuran: Algoritma milih negara sing paling njanjeni adhedhasar heuristic evaluasi. Iku nggunakake strategi panelusuran kaya Best-First Panelusuran, A* Panelusuran, utawa Greedy Panelusuran.
- Ekspansi Negara: Negara sing dipilih ditambahi kanthi ngasilake negara tetanggan. Iki minangka calon potensial kanggo langkah sabanjure.
- Baleni: Proses kasebut diulang maneh, milih lan nggedhekake negara nganti negara tujuan ditemokake utawa kondisi mandap ditemokake.
Contoh: Travelling Salesman Problem(TSP)
Coba Masalah Salesman Traveling, ngendi salesman kudu ngunjungi set kutha lan bali menyang kutha wiwitan nalika nyilikake total jarak lelungan. Pendekatan heuristic bisa dadi Algoritma Nearest Neighbor:
- Mulai ing kutha acak.
- Ing saben langkah, pilih kutha paling cedhak sing durung dibukak minangka tujuan sabanjure.
- Baleni nganti kabeh kutha dibukak, banjur bali menyang kutha wiwitan.
Tuladha Kode ing C++
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
struct City {
int x, y;
};
double distance(const City& city1, const City& city2) {
return std::sqrt(std::pow(city1.x- city2.x, 2) + std::pow(city1.y- city2.y, 2));
}
std::vector<int> nearestNeighbor(const std::vector<City>& cities) {
int numCities = cities.size();
std::vector<int> path(numCities);
std::vector<bool> visited(numCities, false);
path[0] = 0;
visited[0] = true;
for(int i = 1; i < numCities; ++i) {
int currentCity = path[i- 1];
double minDist = std::numeric_limits<double>::max();
int nextCity = -1;
for(int j = 0; j < numCities; ++j) {
if(!visited[j]) {
double dist = distance(cities[currentCity], cities[j]);
if(dist < minDist) {
minDist = dist;
nextCity = j;
}
}
}
path[i] = nextCity;
visited[nextCity] = true;
}
path.push_back(0); // Return to the starting city
return path;
}
int main() {
std::vector<City> cities = {{0, 0}, {1, 3}, {4, 2}, {3, 6}, {7, 1}};
std::vector<int> path = nearestNeighbor(cities);
std::cout << "Traveling Salesman Path: ";
for(int city: path) {
std::cout << city << ";
}
std::cout << std::endl;
return 0;
}
Ing conto iki, Algoritma Nearest Neighbor digunakake kanggo ngatasi Masalah Salesman Traveling. Iki minangka heuristic pendekatan sing milih kutha paling cedhak sing ora dibukak ing saben langkah, nyebabake solusi sing asring nyedhaki optimal.