图的表示
来源:互联网 发布:汉王考勤软件下载 编辑:程序博客网 时间:2024/06/05 02:02
矩阵表示法:不能表示平行边,可以表示自环
空间复杂度V^2,时间复杂度,寻找和某个顶点相邻边的复杂度为V
边表示法:空间复杂度V,时间复杂度 寻找和某个顶点相邻边复杂度为E
邻接表 空间复杂度V+E,用V个头结点表示所有顶点,每个头结点下面连着和它相邻的顶点。可以表示自环和平行边
实现方式
#include <iostream>#include <vector>#include <algorithm>#include <string>using namespace std;struct Node{ int who; //int weight; Node*next;};struct HeadNode{ //int nodeName; int inDegree; Node*link;};class Graph{private: int V; int E; vector<HeadNode*> vec;private: bool connected(int v){ return vec[v]->link != NULL;} Node* rear(int v){ Node* current = vec[v]->link; for(int i = 1; i < vec[v]->inDegree ; i++){ current = current->next; } return current; }public: Graph(int V); int Vs(){ return V;}; int Es(){ return E;}; void addEdge(int v,int w); int degree(int v){ return vec[v]->inDegree;} int maxDegree(); int numOfSelfLoops(); void Print();};Graph::Graph(int V){ this->V = V; this->E = 0; for(int i = 0 ; i <= V ; i++){ HeadNode* newone= new HeadNode; newone->inDegree = 0; newone->link = NULL; vec.push_back(newone); }}void Graph::addEdge(int v,int w){ E++; Node* newone = new Node; newone->who = w; newone->next = NULL; if(connected(v)){ Node* last = rear(v); last->next = newone; } else vec[v]->link = newone; vec[v]->inDegree++; Node* newone2 = new Node; newone2->who = v; newone2->next = NULL; if(connected(w)){ Node* last = rear(w); last->next = newone2; } else vec[w]->link = newone2; vec[w]->inDegree++;}int Graph::maxDegree(){ int max = vec[1]->inDegree; for(int i = 2 ; i <= V ; i++){ if(vec[i]->inDegree>max) max = vec[i]->inDegree; } return max;}int Graph::numOfSelfLoops(){ int cnt = 0; for(int v = 1 ; v <= V; v++){ Node* current = vec[v]->link; while(current->next != NULL){ if(current->who == v) cnt++; current = current->next; } } return cnt;}void Graph::Print(){ cout<<V<<" vertices and "<<E<<" edges"<<endl; for(int i = 1 ; i <= V ; i++){ cout<<"vertices "<<i<<" link: "; if(!connected(i)) { cout<<" null"<<endl; continue; } Node* current = vec[i]->link; while(current != NULL){ cout<<current->who<<", "; current = current->next; } cout<<endl; }}int main(){ Graph a(5); a.addEdge(2,1); a.addEdge(2,3); a.addEdge(3,4); a.addEdge(3,5); a.Print(); return 0;}
0 0
- 图的表示-邻接矩阵表示
- 图的邻接矩阵表示
- 图的数组表示
- 图的矩阵表示
- 图的邻接矩阵表示
- 图的邻接矩阵表示
- 二、图的表示
- 图的表示
- 图的链式表示
- 图的表示--邻接矩阵
- 图的表示
- 图的表示--邻接矩阵
- 图的表示
- 图的表示
- 图的表示
- 图的表示
- 图的表示
- 图的表示
- Atitit.预定义变量与变量预处理器
- 有趣的单机单节点现象
- java中的修饰符final和static
- Atitit.jpg png格式差别以及解决jpg图片不显示的问题
- Spring——AOP
- 图的表示
- 一、hbase的核心数据结构
- Atitit.jpg png格式差别以及解决jpg图片不显示的问题
- maven 手动把本地jar安装到本地仓库,maven手动安装依赖jar包
- SGU 104 Little shop of flowers【DP】
- hdu1556 Color the ball(树状数组)
- hdu1754 I Hate It(单点更新)
- Ubuntu清理无用的软件包级更新源方法
- hdu1394 Minimum Inversion Number(单点更新)