【图】单源最短路径
最短路徑
-
圖上的最短路徑:兩頂點之間經過的邊數最少的路徑;
-
網上的最短路徑:兩頂點之間經過的邊上權值之和最少的路徑(源點->終點)。
a星算法、迪杰斯特拉算法、佛洛依德算法。
迪杰斯特拉算法
單源最短路徑按路徑長度遞增的次序產生最短路徑的算法。過程如下:
找到直接能到達的最短路徑
以最短到達的終點為源點繼續找能直接到達的
更新最短路徑
需要記住路徑和最短路徑
-
最短路徑的值:shortpath[9]
-
最短路徑當前頂點的前一個頂點:path[9]
-
記錄頂點是否被選過:visited[9] = {0};
-
用鄰接矩陣Edge存邊權
-
記錄當前最小值:min
-
min_index = 記錄到達最短路徑的下標
?
創建一個圖:
主函數:?
void main(){Graph g;g.InsertVertex('a');g.InsertVertex('b');g.InsertVertex('c');g.InsertVertex('d');g.InsertVertex('e');g.InsertVertex('f');g.InsertVertex('g');g.InsertVertex('h');g.InsertVertex('i');g.InsertEdge('a', 'b', 1);g.InsertEdge('a', 'c', 5);g.InsertEdge('b', 'c', 3);g.InsertEdge('b', 'd', 7);g.InsertEdge('b', 'e', 5);g.InsertEdge('c', 'e', 1);g.InsertEdge('c', 'f', 7);g.InsertEdge('d', 'g', 3);g.InsertEdge('d', 'e', 2);g.InsertEdge('e', 'g', 6);g.InsertEdge('e', 'h', 9);g.InsertEdge('e', 'f', 3);g.InsertEdge('f', 'h', 5);g.InsertEdge('g', 'h', 2);g.InsertEdge('g', 'i', 7);g.InsertEdge('h', 'i', 4);g.PrintGraph();g.ShortPath('a'); }單元最短路徑ShortPath:
ShortPath(char vertex);輸入點,從該點開始找它為起點的單元最短路徑。
得到下標:
int v = GetVertexIndex(vertex);if (v == -1) return;shortpath:最短路徑的值
path:最短路徑-當前頂點的前一個頂點
visited:記錄頂點是否被選過
int* shortpath = new int[m_NumVertex]; int* path = new int[m_NumVertex]; int* visited = new int[m_NumVertex];初始化數組:
int i, j;for (i = 0; i < m_NumVertex; i++){shortpath[i] = m_Edge[v][i];//把權值存到shortpath中visited[i] = 0;//沒有被訪問-0if (i != v&&shortpath[i]<MAX_WEIGHT)//不是自己到自己 且 可以到達{path[i] = v;//可以到達,v作為其前一個頂點}elsepath[i] = -1;//不能到達-1}visited[v] = 1;訪問完置為1循環計算從當前頂點到其余各頂點的最短路徑
min:最小權值
min_index:目的下標
int min;//min是最小權值int min_index;//min_index是目的下標for (i = 0; i < m_NumVertex - 1; i++){min = MAX_WEIGHT;min_index = -1;for (j = 0; j < m_NumVertex; ++j){//頂點沒有被訪問過 且 權值<最短路徑if (!visited[j] && shortpath[j] < min){//更新最短路徑和其目的下標min = shortpath[j];min_index = j;}}//當前最短路徑目的節點被訪問visited[min_index] = 1;//更新看從min_index到其余沒有找到的路經頂點的權值加上min是否小于原本的權值 //如果小則更新for (j = 0; j < m_NumVertex; j++){int w = m_Edge[min_index][j];//最短路徑目的節點到其他點的權值if (!visited[j] && w < MAX_WEIGHT&&shortpath[min_index]+w<shortpath[j]){shortpath[j] = shortpath[min_index] + w;path[j] = min_index;}}}輸出-釋放
for (i = 0; i < m_NumVertex; i++){cout << vertex << "->" << m_VertexArr[i] << ":" << shortpath[i] << ":" << path[i];//起點->終點:權值:前一個頂點下標cout << endl;}delete[]shortpath;delete[]path;delete[]visited;shortpath = nullptr;path = nullptr;visited = nullptr;總結
- 上一篇: BPG编译出错 undefined re
- 下一篇: 申请sp资质