分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow
也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!
【 声明:版权所有,欢迎转载,请勿用于商业用途。 联系信箱:feixiaoxing @163.com】
前面我们讨论过图的基本结构是什么样的。它可以是矩阵类型的、数组类型的,当然也可以使指针类型的。当然,就我个人而言,比较习惯使用的结构还是链表指针类型的。本质上,一幅图就是由很多节点构成的,每一个节点上面有很多的分支,仅此而已。为此,我们又对原来的结构做了小的改变:
typedef struct _LINE{ int end; int weight; struct _LINE* next;}LINE;typedef struct _VECTEX{ int start; int number; LINE* neighbor; struct _VECTEX* next;}VECTEX;typedef struct _GRAPH{ int count; VECTEX* head;}GRAPH;
为了创建图,首先我们需要创建节点和创建边。不妨从创建节点开始,
VECTEX* create_new_vectex(int start){ VECTEX* pVextex = (VECTEX*)malloc(sizeof(VECTEX)); assert(NULL != pVextex); pVextex->start = start; pVextex->number = 0; pVextex->neighbor = NULL; pVextex->next = NULL; return pVextex;}
接着应该创建边了,
LINE* create_new_line(int end, int weight){ LINE* pLine = (LINE*)malloc(sizeof(LINE)); assert(NULL != pLine); pLine->end = end; pLine->weight = weight; pLine->next = NULL; return pLine;}
有了上面的内容,那么创建一个带有边的顶点就变得很简单了,
VECTEX* create_new_vectex_for_graph(int start, int end, int weight){ VECTEX* pVectex = create_new_vectex(start); assert(NULL != pVectex); pVectex->neighbor = create_new_line(end, weight); assert(NULL != pVectex->neighbor); return pVectex;}
那么,怎么它怎么和graph相关呢?其实也不难。
GRAPH* create_new_graph(int start, int end, int weight){ GRAPH* pGraph = (GRAPH*)malloc(sizeof(GRAPH)); assert(NULL != pGraph); pGraph->count = 1; pGraph->head = create_new_vectex_for_graph(start, end, weight); assert(NULL != pGraph->head); return pGraph;}
有了图,有了边,那么节点和边的查找也不难了。
VECTEX* find_vectex_in_graph(VECTEX* pVectex, int start){ if(NULL == pVectex) return NULL; while(pVectex){ if(start == pVectex->start) return pVectex; pVectex = pVectex->next; } return NULL;}LINE* find_line_in_graph(LINE* pLine, int end){ if(NULL == pLine) return NULL; while(pLine){ if(end == pLine->end) return pLine; pLine = pLine->next; } return NULL;}
总结:
(1)图就是多个链表的聚合
(2)想学好图,最好把前面的链表和指针搞清楚、弄扎实
(3)尽量写小函数,小函数构建大函数,方便阅读和调试