手游英雄杀斩将奖励:一步一步写算法(之图创建)

来源:百度文库 编辑:中财网 时间:2024/05/10 07:31:59

【 声明:版权所有,欢迎转载,请勿用于商业用途。 联系信箱:feixiaoxing @163.com】


前面我们讨论过图的基本结构是什么样的。它可以是矩阵类型的、数组类型的,当然也可以使指针类型的。当然,就我个人而言,比较习惯使用的结构还是链表指针类型的。本质上,一幅图就是由很多节点构成的,每一个节点上面有很多的分支,仅此而已。为此,我们又对原来的结构做了小的改变:

view plaincopy to clipboardprint?

  1. typedef struct _LINE
  2. {
  3. int end;
  4. int weight;
  5. struct _LINE* next;
  6. }LINE;
  7. typedef struct _VECTEX
  8. {
  9. int start;
  10. int number;
  11. LINE* neighbor;
  12. struct _VECTEX* next;
  13. }VECTEX;
  14. typedef struct _GRAPH
  15. {
  16. int count;
  17. VECTEX* head;
  18. }GRAPH;
为了创建图,首先我们需要创建节点和创建边。不妨从创建节点开始,

view plaincopy to clipboardprint?

  1. VECTEX* create_new_vectex(int start)
  2. {
  3. VECTEX* pVextex = (VECTEX*)malloc(sizeof(VECTEX));
  4. assert(NULL != pVextex);
  5. pVextex->start = start;
  6. pVextex->number = 0;
  7. pVextex->neighbor = NULL;
  8. pVextex->next = NULL;
  9. return pVextex;
  10. }
接着应该创建边了,

view plaincopy to clipboardprint?

  1. LINE* create_new_line(int end, int weight)
  2. {
  3. LINE* pLine = (LINE*)malloc(sizeof(LINE));
  4. assert(NULL != pLine);
  5. pLine->end = end;
  6. pLine->weight = weight;
  7. pLine->next = NULL;
  8. return pLine;
  9. }
有了上面的内容,那么创建一个带有边的顶点就变得很简单了,

view plaincopy to clipboardprint?

  1. VECTEX* create_new_vectex_for_graph(int start, int end, int weight)
  2. {
  3. VECTEX* pVectex = create_new_vectex(start);
  4. assert(NULL != pVectex);
  5. pVectex->neighbor = create_new_line(end, weight);
  6. assert(NULL != pVectex->neighbor);
  7. return pVectex;
  8. }
那么,怎么它怎么和graph相关呢?其实也不难。

view plaincopy to clipboardprint?

  1. GRAPH* create_new_graph(int start, int end, int weight)
  2. {
  3. GRAPH* pGraph = (GRAPH*)malloc(sizeof(GRAPH));
  4. assert(NULL != pGraph);
  5. pGraph->count = 1;
  6. pGraph->head = create_new_vectex_for_graph(start, end, weight);
  7. assert(NULL != pGraph->head);
  8. return pGraph;
  9. }
有了图,有了边,那么节点和边的查找也不难了。

view plaincopy to clipboardprint?

  1. VECTEX* find_vectex_in_graph(VECTEX* pVectex, int start)
  2. {
  3. if(NULL == pVectex)
  4. return NULL;
  5. while(pVectex){
  6. if(start == pVectex->start)
  7. return pVectex;
  8. pVectex = pVectex->next;
  9. }
  10. return NULL;
  11. }
  12. LINE* find_line_in_graph(LINE* pLine, int end)
  13. {
  14. if(NULL == pLine)
  15. return NULL;
  16. while(pLine){
  17. if(end == pLine->end)
  18. return pLine;
  19. pLine = pLine->next;
  20. }
  21. return NULL;
  22. }


总结:

(1)图就是多个链表的聚合

(2)想学好图,最好把前面的链表和指针搞清楚、弄扎实

(3)尽量写小函数,小函数构建大函数,方便阅读和调试