在前面兩節圖和圖的最小生成樹之PRim算法的基礎上,這里給出另外一種求解MST(最小生成樹)的算法—–Kruskal算法。
Kruskal算法可以概括為:
取出連通無向圖G的所有邊。從第一步形成的邊集合中選取權值最小的邊,加入最小生成樹邊集合T中。求出第二步中選出邊的兩端頂點,判斷他們所在頂點集的關系以確認是否存在回路。若不存在回路,則確認將此最小邊加入T中,若存在回路,則丟棄。 同Prim算法,我們用下面這一連通無向圖作為示例:
下面給出實現代碼以及測試代碼:(在圖以及Prim算法的基礎上增加而來,若讀者覺得閱讀有困難,可參看前兩節文章)
#include<iostream>#include<cstdlib>#include<vector>using namespace std;/*節點類*/class Node{public: Node(char identifier = 0); char m_identifier; //頂點編號 bool m_isVisited; //頂點訪問標志位:true表示已經被訪問};Node::Node(char identifier){ m_identifier = identifier; m_isVisited = false;}/*邊類,用于輔助實現生成最小生成樹*/class Edge{public: Edge(int NodeIndexA = 0, int NodeIndexB = 0, int WeightValue = 0); int m_NodeIndexA, m_NodeIndexB; //邊的兩端點(索引),這里以無向圖為例 int m_weightValue; //邊的權值 bool m_selected; //選擇標志位,true表示已被選擇};Edge::Edge(int NodeIndexA, int NodeIndexB, int WeightValue){ m_NodeIndexA = NodeIndexA; m_NodeIndexB = NodeIndexB; m_weightValue = WeightValue; m_selected = false; //初始時未被選擇}/*圖類*/class Graph{public: Graph(int capacity); ~Graph(); int getGraphSize(); //獲取當前圖的大小 void resetNode(); //重置所有頂點的訪問標志位為false,未訪問 bool addNode(Node *pNode); //添加新頂點 bool addEdgeForUndirectedGraph(int row, int col, int val = 1); //添加邊以構造無向圖,val表示權值,默認權值1 bool addEdgeForDirectedGraph(int row, int col, int val = 1); //添加邊以構造有向圖,val表示權值,默認權值1 void printMatrix(); //打印鄰接矩陣 void depthFirstTraverse(int nodeIndex); //深度優先遍歷,指定第一個點 void widthFirstTraverse(int nodeIndex); //廣度優先遍歷,指定第一個點 void MSTPrim(int nodeIndex); //Prim算法求最小生成樹,指定第一個點 void MSTKruskal(); //Kruskal算法求最小生成樹,指定第一個點private: bool getValueOfEdge(int row, int col, int &val); //獲取邊權值 void widthFirstTraverseImplement(vector<int> preVec); //利用vector實現廣度優先遍歷 int getMinEdge(vector<Edge> edgeVec); //最小生成樹算法輔助函數,用于在邊集中選擇權值最小的邊 bool isInSet(vector<int> nodeSet, int target); //Kruskal輔助函數,用于判斷指定頂點是否在給定點集中 void mergeNodeSets(vector<int> &nodeSetA, vector<int> nodeSetB); //Kruscal輔助函數,用于合并兩個點集 int m_iCapacity; //圖容量,即申請的數組空間最多可容納的頂點個數 int m_iNodeCount; //圖的現有頂點個數 Node *m_pNodeArray; //存放頂點的數組 int *m_pMatrix; //為了方便,用一維數組存放鄰接矩陣 Edge *m_pEgde; //邊指針,存儲最小生成樹的邊};Graph::Graph(int capacity){ m_iCapacity = capacity; m_iNodeCount = 0; m_pNodeArray = new Node[m_iCapacity]; m_pMatrix = new int[m_iCapacity*m_iCapacity]; for (int i = 0;i < m_iCapacity*m_iCapacity;i++) //初始化鄰接矩陣 { m_pMatrix[i] = 0; } m_pEgde = new Edge[m_iCapacity - 1]; //最小生成樹節點和邊數量關系}Graph::~Graph(){ delete []m_pNodeArray; delete []m_pMatrix; delete []m_pEgde;}int Graph::getGraphSize(){ return m_iNodeCount;}void Graph::resetNode(){ for (int i = 0;i < m_iNodeCount;i++) { m_pNodeArray[i].m_isVisited = false; }}bool Graph::addNode(Node *pNode){ if (pNode == NULL) return false; m_pNodeArray[m_iNodeCount].m_identifier = pNode->m_identifier; m_iNodeCount++; return true;}bool Graph::addEdgeForUndirectedGraph(int row, int col, int val){ if (row < 0 || row >= m_iCapacity) return false; if (col < 0 || col >= m_iCapacity) return false; m_pMatrix[row*m_iCapacity + col] = val; m_pMatrix[col*m_iCapacity + row] = val; return true;}bool Graph::addEdgeForDirectedGraph(int row, int col, int val){ if (row < 0 || row >= m_iCapacity) return false; if (col < 0 || col >= m_iCapacity) return false; m_pMatrix[row*m_iCapacity + col] = val; return true;}void Graph::printMatrix(){ for (int i = 0;i < m_iCapacity;i++) { for (int k = 0;k < m_iCapacity;k++) cout << m_pMatrix[i*m_iCapacity + k] << " "; cout << endl; }}void Graph::depthFirstTraverse(int nodeIndex){ int value = 0; //訪問第一個頂點 cout << m_pNodeArray[nodeIndex].m_identifier << " "; m_pNodeArray[nodeIndex].m_isVisited = true; //訪問其他頂點 for (int i = 0;i < m_iCapacity;i++) { getValueOfEdge(nodeIndex, i, value); if (value != 0) //當前頂點與指定頂點連通 { if (m_pNodeArray[i].m_isVisited == true) //當前頂點已被訪問 continue; else //當前頂點沒有被訪問,則遞歸 { depthFirstTraverse(i); } } else //沒有與指定頂點連通 { continue; } }}void Graph::widthFirstTraverse(int nodeIndex){ //訪問第一個頂點 cout << m_pNodeArray[nodeIndex].m_identifier << " "; m_pNodeArray[nodeIndex].m_isVisited = true; vector<int> curVec; curVec.push_back(nodeIndex); //將第一個頂點存入一個數組 widthFirstTraverseImplement(curVec);}void Graph::widthFirstTraverseImplement(vector<int> preVec){ int value = 0; vector<int> curVec; //定義數組保存當前層的頂點 for (int j = 0;j < (int)preVec.size();j++) //依次訪問傳入數組中的每個頂點 { for (int i = 0;i < m_iCapacity;i++) //傳入的數組中的頂點是否與其他頂點連接 { getValueOfEdge(preVec[j], i, value); if (value != 0) //連通 { if (m_pNodeArray[i].m_isVisited==true) //已經被訪問 { continue; } else //沒有被訪問則訪問 { cout << m_pNodeArray[i].m_identifier << " "; m_pNodeArray[i].m_isVisited = true; //保存當前點到數組 curVec.push_back(i); } } } } if (curVec.size()==0) //本層次無被訪問的點,則終止 { return; } else { widthFirstTraverseImplement(curVec); }}bool Graph::getValueOfEdge(int row, int col, int &val){ if (row < 0 || row >= m_iCapacity) return false; if (col < 0 || col >= m_iCapacity) return false; val = m_pMatrix[row*m_iCapacity + col]; return true;}void Graph::MSTPrim(int nodeIndex){ int value = 0; //存儲當前邊的權值 int edgeCount = 0; //已選出的邊數量,用以判斷算法終結 vector<int> nodeVec; //存儲點(索引)集的數組 vector<Edge> edgeVec; //存儲邊的數組 cout << m_pNodeArray[nodeIndex].m_identifier << endl; nodeVec.push_back(nodeIndex); m_pNodeArray[nodeIndex].m_isVisited = true; while (edgeCount < m_iCapacity - 1) { int temp = nodeVec.back(); //將當前頂點索引復制給temp for (int i = 0;i < m_iCapacity;i++) //循環判斷每一個頂點與當前頂點連接情況 { getValueOfEdge(temp, i, value); if (value != 0) //連通 { if (m_pNodeArray[i].m_isVisited == true) //已經被訪問 continue; else //未被訪問,則將邊放入被選邊集合 { Edge edge(temp, i, value); edgeVec.push_back(edge); } } } /*選擇最小邊*/ int edgeIndex = getMinEdge(edgeVec); if (edgeIndex == -1) { cout << "獲取最小邊失敗,請重置后再試!" << endl; break; } edgeVec[edgeIndex].m_selected = true; //設置選擇標志位為true,已被選擇 cout << edgeVec[edgeIndex].m_NodeIndexA << "---" << edgeVec[edgeIndex].m_NodeIndexB<<" "; cout << edgeVec[edgeIndex].m_weightValue << endl; m_pEgde[edgeCount] = edgeVec[edgeIndex]; edgeCount++; /*尋找當前選擇的最小邊相連的下一個頂點*/ int nextNodeIndex = edgeVec[edgeIndex].m_NodeIndexB; nodeVec.push_back(nextNodeIndex); m_pNodeArray[nextNodeIndex].m_isVisited = true; cout << m_pNodeArray[nextNodeIndex].m_identifier << endl; } cout << "最小生成樹計算完畢,如上所示!";}void Graph::MSTKruskal(){ int value = 0; //存儲當前邊的權值 int edgeCount = 0; //已選出的邊數量 /*存放節點集合的數組,不同于Prim,Kruskal算法過程中可能出現多個點集*/ vector<vector<int>> nodeSets; /*取出所有邊*/ vector<Edge> edgeVec; for (int i = 0;i < m_iCapacity;i++) //去鄰接矩陣的右上角的三角部分,不含對角線。無向圖鄰接矩陣對稱 { for (int k = i + 1;k < m_iCapacity;k++) { getValueOfEdge(i, k, value); if (value != 0) { Edge edge(i, k, value); edgeVec.push_back(edge); } } } /*循環尋找最小生成樹的邊*/ while (edgeCount < m_iCapacity - 1) { int minEdgeIndex = getMinEdge(edgeVec); edgeVec[minEdgeIndex].m_selected = true; //選出最小邊,并標記為已選 int nodeAIndex = edgeVec[minEdgeIndex].m_NodeIndexA; int nodeBIndex = edgeVec[minEdgeIndex].m_NodeIndexB; //找出最小邊兩端頂點 bool nodeAIsInSet = false; //標記某個頂點是否在指定點集中 bool nodeBIsInSet = false; int nodeAInSetLabel = -1; //某個頂點所在點集的索引 int nodeBInSetLabel = -1; for (int i = 0;i < (int)nodeSets.size();i++) //尋找A頂點所在點集 { nodeAIsInSet = isInSet(nodeSets[i], nodeAIndex); if (nodeAIsInSet) { nodeAInSetLabel = i; //保存當前點集索引 } } for (int i = 0;i < (int)nodeSets.size();i++) //尋找B頂點所在點集 { nodeBIsInSet = isInSet(nodeSets[i], nodeBIndex); if (nodeBIsInSet) { nodeBInSetLabel = i; //保存當前點集索引 } } /*根據結果做相應處理*/ if (nodeAInSetLabel == -1 && nodeBInSetLabel == -1) //兩頂點均不在已有點集中 { //建立新的點集 vector<int> vec; vec.push_back(nodeAIndex); vec.push_back(nodeBIndex); nodeSets.push_back(vec); } else if (nodeAInSetLabel == -1 && nodeBInSetLabel != -1) //某頂點在已有點集中 { //將另外一個節點加入已有點集 nodeSets[nodeBInSetLabel].push_back(nodeAIndex); } else if (nodeAInSetLabel != -1 && nodeBInSetLabel == -1) { nodeSets[nodeAInSetLabel].push_back(nodeBIndex); } else if (nodeAInSetLabel != -1 && nodeBInSetLabel != -1 && nodeAInSetLabel != nodeBInSetLabel) //兩個頂點在不同的點集中 { //合并兩個集合,到前一參數點集,并將頂點從第二個參數點集刪除 mergeNodeSets(nodeSets[nodeAInSetLabel], nodeSets[nodeBInSetLabel]); for (int k = nodeBInSetLabel;k < (int)nodeSets.size()-1;k++) { nodeSets[k] = nodeSets[k + 1]; } } else if (nodeAInSetLabel != -1 && nodeBInSetLabel != -1 && nodeAInSetLabel == nodeBInSetLabel) //兩個頂點在同一點集 { //存在回路,放棄當前邊 continue; } m_pEgde[edgeCount] = edgeVec[minEdgeIndex]; edgeCount++; cout << edgeVec[minEdgeIndex].m_NodeIndexA << "---" << edgeVec[minEdgeIndex].m_NodeIndexB << " "; cout << edgeVec[minEdgeIndex].m_weightValue << endl; }}int Graph::getMinEdge(vector<Edge> edgeVec){ int minWeight = 0; //用于輔助選擇最小權值邊 int edgeIndex = 0; //用于存儲最小邊索引 int i = 0; /*找出第一條未被選擇的邊*/ for (;i < (int)edgeVec.size();i++) { if (edgeVec[i].m_selected == false) //當前邊未被選擇 { minWeight = edgeVec[i].m_weightValue; edgeIndex = i; break; } } if (minWeight == 0) //邊集所有邊被訪問 { return -1; } for (;i < (int)edgeVec.size();i++) { if (edgeVec[i].m_selected == true) continue; else { if (minWeight > edgeVec[i].m_weightValue) { minWeight = edgeVec[i].m_weightValue; edgeIndex = i; } } } return edgeIndex;}bool Graph::isInSet(vector<int> nodeSet, int target){ for (int i = 0;i < (int)nodeSet.size();i++) { if (nodeSet[i] == target) return true; } return false;}void Graph::mergeNodeSets(vector<int> &nodeSetA, vector<int> nodeSetB){ for (int i = 0;i < (int)nodeSetB.size();i++) { nodeSetA.push_back(nodeSetB[i]); }}int main(){ Graph *pGraph = new Graph(6); cout << "初始化頂點中……" << endl; Node *pNodeA = new Node('A'); Node *pNodeB = new Node('B'); Node *pNodeC = new Node('C'); Node *pNodeD = new Node('D'); Node *pNodeE = new Node('E'); Node *pNodeF = new Node('F'); cout << "添加頂點至圖中……" << endl; pGraph->addNode(pNodeA); pGraph->addNode(pNodeB); pGraph->addNode(pNodeC); pGraph->addNode(pNodeD); pGraph->addNode(pNodeE); pGraph->addNode(pNodeF); pGraph->addEdgeForUndirectedGraph(0, 1, 6); pGraph->addEdgeForUndirectedGraph(0, 4, 5); pGraph->addEdgeForUndirectedGraph(0, 5, 1); pGraph->addEdgeForUndirectedGraph(1, 5, 2); pGraph->addEdgeForUndirectedGraph(1, 2, 3); pGraph->addEdgeForUndirectedGraph(2, 5, 8); pGraph->addEdgeForUndirectedGraph(2, 3, 7); pGraph->addEdgeForUndirectedGraph(3, 5, 4); pGraph->addEdgeForUndirectedGraph(3, 4, 2); pGraph->addEdgeForUndirectedGraph(4, 5, 9); cout << "鄰接矩陣如下:" << endl; pGraph->printMatrix(); cout << endl << endl; cout << "深度優先遍歷:" << endl; pGraph->depthFirstTraverse(0); cout << endl << endl; pGraph->resetNode(); cout << "廣度優先遍歷:" << endl; pGraph->widthFirstTraverse(0); cout << endl << endl; pGraph->resetNode(); cout << "最小生成樹為:" << endl; pGraph->MSTKruskal(); cout << endl; system("pause");} 測試結果如下:
在文章開始對Kruskal算法的描述中,涉及到循環的每一次都要尋找最小邊的問題。我們可以換一種思路,作如下描述:
對G的邊以飛降序權重排序。對于排序表中的每條邊,如果現在把它加入T不會形成回路,則將其加入T集合中,否則丟棄。有興趣的讀者可以自己用這一種算法描述來改進Krukal算法,這樣就不需要每進行一次循環就需要調用getMinEdge()函數,可以減少算法時間開銷。這樣一來,若G含有m條邊,則其算法時間復雜度為O(m * log m)。
新聞熱點
疑難解答
圖片精選