图的相关操作
Posted zhishoumuguinian
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了图的相关操作相关的知识,希望对你有一定的参考价值。
1 #include <iostream> 2 3 using namespace std; 4 const int MaxNum = 100; 5 6 typedef struct srcNode { 7 int Vem; 8 struct srcNode * next; 9 } srcNode; 10 11 typedef struct vNode { 12 char data; 13 srcNode *src; 14 } vNode; 15 16 typedef struct GNode { 17 int vNum, srcNum; 18 vNode vNodeList[MaxNum]; 19 } Graph, GNode; 20 21 22 void BFS(Graph *G) { 23 int v[MaxNum*MaxNum]; 24 int front = -1, rear = -1; 25 bool visited[MaxNum]; 26 for(int i=0; i<G->vNum; ++i) { 27 visited[i] = false; 28 } 29 v[++rear] = 0; 30 while(rear!=front) { 31 int vnow = v[++front]; 32 if(!visited[vnow]) { 33 34 cout<<G->vNodeList[vnow].data<<endl; 35 visited[vnow] = true; 36 srcNode *p = G->vNodeList[vnow].src; 37 while(p) { 38 v[++rear] = p->Vem; 39 p = p->next; 40 } 41 42 } 43 // cout<<"队列中的元素:"; 44 // for(int k=front+1; k<=rear; k++){ 45 // cout<< G->vNodeList[v[k]].data <<" "; 46 // } 47 // cout<<endl; 48 } 49 } 50 51 52 void DFS(Graph *G){ 53 int stack[MaxNum*MaxNum]; 54 int top = -1; 55 bool visited[G->vNum]; 56 for(int i=0; i<G->vNum; ++i){ 57 visited[i] = false; 58 } 59 60 stack[++top] = 0; 61 while(top!=-1){ 62 int vnow = stack[top--]; 63 if(!visited[vnow]){ 64 cout<<G->vNodeList[vnow].data<<endl; 65 visited[vnow] = true; 66 srcNode *p = G->vNodeList[vnow].src; 67 while(p) { 68 stack[++top] = p->Vem; 69 p = p->next; 70 } 71 } 72 } 73 } 74 75 76 Graph *createGraph(char v[], int src[][6], int n) { 77 Graph *G = new Graph(); 78 G->srcNum = 7; 79 G->vNum = 6; 80 for(int i=0; i<n; i++) { 81 G->vNodeList[i].data = v[i]; 82 G->vNodeList[i].src = NULL; 83 84 for(int j=0; j<n; j++) { 85 if(src[i][j] != 0) { 86 srcNode *srcNow = new srcNode(); 87 srcNow->Vem = j; 88 srcNow->next = G->vNodeList[i].src; 89 G->vNodeList[i].src = srcNow; 90 } 91 } 92 } 93 return G; 94 } 95 96 void show(Graph *G) { 97 for(int i=0; i<G->vNum; i++) { 98 srcNode *p = G->vNodeList[i].src; 99 while(p) { 100 cout<<G->vNodeList[p->Vem].data<<" "; 101 p = p->next; 102 } 103 cout<<endl; 104 } 105 } 106 107 int main() { 108 char v[]= {‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘}; 109 int src[6][6]= { 110 {0,1,1,0,1,0}, 111 {1,0,0,0,1,0}, 112 {1,0,0,0,0,0}, 113 {0,0,0,0,1,1}, 114 {1,1,0,1,0,1}, 115 {0,0,0,1,1,0}, 116 }; 117 118 Graph *G = createGraph(v, src, 6); 119 // show(G); 120 // BFS(G); 121 DFS(G); 122 }
以上是关于图的相关操作的主要内容,如果未能解决你的问题,请参考以下文章