当前位置:   article > 正文

无向图的表示:邻接矩阵和邻接表_对于如图8.36所示的无向图,写出该图的邻接矩阵和邻接表。

对于如图8.36所示的无向图,写出该图的邻接矩阵和邻接表。

这里将一个无向图用邻接表和邻接矩阵表示。

输入:顶底个数n,图中的各个边(用两个顶点表示)。

输出:这个无线图的邻接矩阵和邻接表,其中邻接表中的链接按元素大小升序排列。

先给出一个例子说明。假设有无向图如下,则其邻接矩阵和邻接表如提示框中所示(其实就是下面程序的输出)。


下面是程序的代码:

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. //图的表示,输入节点个数和边,构造图的邻接矩阵和邻接表
  4. //邻接表中的链表节点
  5. struct vNode{
  6. int value;
  7. struct vNode* next;
  8. };
  9. //向邻接表中插入一个数据,并保证邻接表的有序性
  10. void insertIntoAdjVertics(struct vNode** adjVertics,int start,int end){
  11. struct vNode* node = (struct vNode*)malloc(sizeof(struct vNode));
  12. struct vNode* head = adjVertics[start];
  13. node->value = end;
  14. node->next = NULL;
  15. if(head == NULL){
  16. adjVertics[start] = node;
  17. return;
  18. }
  19. if(head->next==NULL&&head->value>end){
  20. node->next = head;
  21. adjVertics[start] = node;
  22. return;
  23. }
  24. while(head->next!=NULL && head->next->value<end){
  25. head = head->next;
  26. }
  27. if(head->next==NULL){
  28. head->next = node;
  29. return;
  30. }
  31. node->next = head->next;
  32. head->next = node;
  33. }
  34. //打印邻接矩阵
  35. void displayNeighborMatrix(int** neighborMatrix,int n){
  36. int i,j;
  37. printf("\n");
  38. for(i=0;i<n;i++){
  39. for(j=0;j<n;j++){
  40. printf("%d ",neighborMatrix[i][j]);
  41. }
  42. printf("\n");
  43. }
  44. }
  45. //打印邻接表
  46. void displayAdjVertice(struct vNode** adjVertics,int n){
  47. int i;
  48. for(i=0;i<n;i++){
  49. struct vNode* head = adjVertics[i];
  50. printf("%d: ",i);
  51. while(head!=NULL){
  52. printf("->%d ",head->value);
  53. head = head->next;
  54. }
  55. printf("\n");
  56. }
  57. }
  58. int main() {
  59. int n,i,j;
  60. int** neighborMatrix;
  61. struct vNode** adjVertics;
  62. int start,end;
  63. printf("input vertex number: ");
  64. scanf("%d",&n);
  65. //初始化邻接矩阵
  66. neighborMatrix = (int**)malloc(sizeof(int*)*n);
  67. for(i=0;i<n;i++){
  68. neighborMatrix[i] = (int*)malloc(sizeof(int)*n);
  69. for(j=0;j<n;j++){
  70. neighborMatrix[i][j] = 0;
  71. }
  72. }
  73. adjVertics = (struct vNode**)malloc(sizeof(struct vNode*)*n);
  74. for(i=0;i<n;i++){
  75. adjVertics[i] = NULL;
  76. }
  77. //输入定点,格式为 1 2
  78. printf("input start and end vertex, format 1 2, stop by -1. \n");
  79. while(1){
  80. scanf("%d",&start);
  81. if(start==-1){
  82. break;
  83. }
  84. scanf("%d",&end);
  85. neighborMatrix[start][end] = 1; //对称矩阵
  86. neighborMatrix[end][start] = 1;
  87. insertIntoAdjVertics(adjVertics,start,end);
  88. insertIntoAdjVertics(adjVertics,end,start);
  89. }
  90. displayNeighborMatrix(neighborMatrix,n);
  91. printf("-------------\n");
  92. displayAdjVertice(adjVertics,n);
  93. return EXIT_SUCCESS;
  94. }


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Guff_9hys/article/detail/874018
推荐阅读
相关标签
  

闽ICP备14008679号