首页 > 代码库 > 邻接矩阵和邻接表

邻接矩阵和邻接表

图有两种存储方式,邻接表和邻接矩阵。

稀疏图一般用邻接链表,稠密图一般用邻接矩阵。

具体实现如下:

  1 //  2 //邻接矩阵
  3 class Graph {
  4 private:
  5     //指向邻接矩阵
  6     int **mat;
  7     //n为顶点个数
  8     int n;
  9 public:
 10     Graph(int input_n) {
 11         n = input_n;
 12         mat = new int *[n];
 13         for (int i = 0; i < n; ++i) {
 14             mat[i] = new int[n];
 15             memset(mat[i], 0, sizeof(int) * n);
 16         }
 17     }
 18     ~Graph() {
 19         for (int i = 0; i< n; ++i) {
 20             delete[] mat[i];
 21         }
 22         delete[] mat;
 23     }
 24     //flag=0为有向图, flag=1为无向图
 25     void insert(int x,int y, int flag){
 26         arr[x][y]=1;
 27         if(flag==1){
 28             arr[y][x]=1;
 29         }
 30     }
 31     void output() {
 32         for(int i=0;i<n;i++){
 33             for(int j=0;j<n;j++){
 34                 cout<<mat[i][j]<<" ";
 35             }
 36             cout<<endl;
 37         }
 38     }
 39 };
 40 
 41 
 42 
 43 
 44 //邻接表
 45 class LinkedListNode {
 46 public:
 47     int vertex;
 48     LinkedListNode *next;
 49     LinkedListNode(int vertex_input) {
 50         vertex = vertex_input;
 51         next = NULL;
 52     }
 53 };
 54 class LinkedList {
 55 public:
 56     LinkedListNode *head;
 57     LinkedList() {
 58         head = NULL;
 59     }
 60     ~LinkedList() {
 61         while (head != NULL) {
 62             LinkedListNode *delete_node = head;
 63             head = head->next;
 64             delete delete_node;
 65         }
 66     }
 67     void insert(int vertex) {
 68         //这种插入方法使得输出时顺序是与插入顺序相反的
 69         LinkedListNode *node = new LinkedListNode(vertex);
 70         node->next = head;
 71         head = node;
 72     }
 73 };
 74 class Graph {
 75 private:
 76     LinkedList *edges;
 77     int n;
 78 public:
 79     Graph(int input_n){
 80         n=input_n;
 81         edges=new LinkedList[n];
 82     }
 83     ~Graph(){
 84         delete[] edges;
 85     }
 86     //flag=0为有向图,flag=1为无向图
 87     void insert(int flag, int x,int y){
 88         edges[x].insert(y);
 89         if(flag==1){
 90             edges[y].insert(x);
 91         }
 92     }
 93     void output(){
 94         for(int i=0;i<n;i++){
 95             cout<<i<<":";
 96             for(auto j=edges[i].head;j!=NULL;j=j->next){
 97                 cout<<" ";
 98                 cout<<j->vertex;
 99             }
100             cout<<endl;
101         }
102     }
103 };

 

邻接矩阵和邻接表