Original: Step-by-step writing algorithm (Prim algorithm)
"Disclaimer: Copyright, welcome reprint, please do not use for commercial purposes. Contact mailbox: feixiaoxing @163.com "
C) write a minimal spanning tree that involves creating, picking, and adding processes
mini_generate_tree* get_mini_tree_from_graph (graph* pgraph) {mini_generate_tree* pminitree;dir_line pDirLine;if ( NULL = = Pgraph | | NULL = = Pgraph->head) return null;pminitree = (mini_generate_tree*) malloc (sizeof (Mini_generate_tree)); Assert (null ! = Pminitree); memset (pminitree, 0, sizeof (mini_generate_tree));p minitree->node_num = 1;pminitree->pnode = (int* ) malloc (sizeof (int) * pgraph->count); memset (pminitree->pnode, 0, sizeof (int) * Pgraph->count);p minitree- >pnode[0] = pgraph->head->start;while (1) {memset (&pdirline, 0, sizeof (dir_line)); get_dir_line_from_ Graph (pgraph, pminitree, &pdirline); if (Pdirline.start = = 0) break;pminitree->line_num ++;insert_line_into_ Queue (&pminitree->pline, Pdirline.start, Pdirline.end, pdirline.weight); Insert_node_into_mini_tree (& Pdirline, Pminitree);} return pminitree;}
D) Build a selection function to select the most appropriate edge
void Get_dir_line_from_graph (graph* pgraph, mini_generate_tree* pminitree, dir_line* pdirline) {DIR_LINE* pHead;DIR_ line* prev; vectex* Pvectex; line* pline;int Index;int start;phead = null;for (index = 0; index < pminitree->node_num; index++) {start = pminitree- >pnode[index];p Vectex = find_vectex_in_graph (Pgraph->head, start);p line = Pvectex->neighbor;while (pLine) { Insert_line_into_queue (&phead, start, Pline->end, pline->weight);p line = Pline->next;}} if (null = = Phead) return;delete_unvalid_line_from_list (&phead, Pminitree); if (null = = Phead) return;sort_for_line_ List (&phead); Memmove (Pdirline, Phead, sizeof (Dir_line)), while (phead) {prev = Phead;phead = Phead->next;free ( prev);} return;}
e) Add a node function to incorporate the points that are not yet the smallest spanning tree into the smallest spanning tree
void Insert_node_into_mini_tree (dir_line* pLine, mini_generate_tree* pminitree) {int index;for (index = 0; Index < pminitree->node_num; Index + +) {if (Pline->start = = Pminitree->pnode[index]) {pminitree->pnode[pminitree->node_num++] = pLine- >end;return;}} pminitree->pnode[pminitree->node_num++] = Pline->start;return;}
Precautions:
(1) d, E is the sub-function called in C, if you look at it, we understand.
(2) The minimum spanning tree is written in the top-down order, although the sub-function in C is complete, but there are two sub-functions in D that are not landed
(3) The function delete_unvalid_line_from_list and sort_for_line_list in D will continue to be introduced in the next article.
(4) As long as the algorithm can be written in accordance with the manual calculation process, basically the problem is not big, but some details should be careful attention
adjourned
Step-by-step write algorithm (in the prim algorithm)