구현 - 다익스트라 dijkstra, 플로이드 floyd
2018. 3. 12. 06:26
main.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #include "WGraphDijkstra.h" #include "WGraphFloyd.h" int main() { WGraphDijkstra g; g.load(ifstream("grap.txt")); g.display(); cout << endl; g.dijkstra_path(0); WGraphFloyd f; f.load(ifstream("grap.txt")); f.display(); cout << endl; f.floyd_path(); f.printResult(); } | cs |
코드 출처 : c++로 쉽게 풀어쓴 알고리즘
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | #pragma once #include "WGraph.h" class WGraphFloyd : public WGraph { int dist[MAX_VTXS][MAX_VTXS]; public: void floyd_path() { for (int i = 0; i < size; ++i) for (int j = 0; j < size; ++j) dist[i][j] = getEdge(i, j); for (int k = 0; k < size; ++k) { for (int i = 0; i < size; ++i) for (int j = 0; j < size; ++j) if (dist[i][k] + dist[k][j] < dist[i][j]) dist[i][j] = dist[i][k] + dist[k][j]; } } void printResult() { for (int i = 0; i < size; ++i) { for (int j = 0; j < size; ++j) cout << setw(4) << dist[i][j]; cout << endl; } cout << endl; } }; | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | #pragma once #include "WGraph.h" class WGraphDijkstra : public WGraph { int dist[MAX_VTXS]; bool found[MAX_VTXS]; public: int nearest_vtx_idx() { int min = INF; int minIndex = -1; for (int i = 0; i < size; ++i) { if (dist[i] < min && !found[i]) { min = dist[i]; minIndex = i; } } return minIndex; } void print_distances() { for (int i = 0; i < size; ++i) { cout << dist[i] << " "; } cout << endl; } void dijkstra_path(int start) { for (int i = 0; i < size; ++i) { dist[i] = getEdge(start, i); found[i] = false; } found[start] = true; dist[start] = 0; for (int i = 0; i < size; ++i) { cout << "Step : " << i + 1 << endl; print_distances(); int u = nearest_vtx_idx(); found[u] = true; for (int w = 0; w < size; ++w) { if (found[w] == false) { if (dist[u] + getEdge(u, w) < dist[w]) dist[w] = dist[u] + getEdge(u, w); } } } } }; | cs |
'프로그래밍' 카테고리의 다른 글
구현 - 병합 정렬, 퀵 정렬, 기수 정렬 (0) | 2018.03.14 |
---|---|
구현 - 버블정렬, 선택 정렬, 삽입 정렬, 셸 정렬 (0) | 2018.03.14 |
구현 - 프림 알고리즘 (0) | 2018.03.12 |
구현 - 가중치 그래프와 크루스칼 알고리즘 (0) | 2018.03.11 |
구현 - 인접행렬과 인접리스트를 이용한 BFS, DFS (0) | 2018.03.10 |