Advertisement
Guest User

Untitled

a guest
Jun 26th, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. typedef struct node
  4. {
  5. int adj;
  6. }verNode;
  7. typedef struct graph
  8. {
  9. verNode **matrix;
  10. int* verList;
  11. int verNum;
  12. int edgeNum;
  13. }graph;
  14. graph* createGraph(int v)
  15. {
  16. graph *g=malloc(sizeof(graph));
  17. if(!g) exit(-1);
  18. g->matrix=NULL;
  19. g->verList=malloc(sizeof(verNode)*v);
  20. if(!g->verList) exit(-1);
  21. g->verNum=v;
  22. printf("Enter the value of vertices:n");
  23. for(int i=0;i<g->verNum;i++)
  24. {
  25. printf("Enter the value of vertex %d:n",i);
  26. scanf("%d",g->verList);
  27. }
  28. return g;
  29. }
  30. verNode** createMatrix(graph *g)
  31. {
  32. if(!g) exit(-1);
  33. g->matrix=malloc(sizeof(int*)*g->verNum*g->verNum);
  34. if(!g->matrix) exit(-1);
  35. for(int i=0;i<g->verNum;i++)
  36. {
  37. for(int j=0;j<g->verNum;j++)
  38. {
  39. (*g->matrix)->adj=0; //error:EXC_BAD_ACCESS (code=1, //address=0x0)
  40. }
  41. }
  42. return g->matrix;
  43. }
  44. void addEdge(graph *g,int v)
  45. {
  46. if(!g||!g->matrix||!g->verList) exit(-1);
  47. int ver1,ver2;
  48. g->edgeNum=v;
  49. printf("Enter the indexes of the vertices:n");
  50. for(int i=0;i<g->edgeNum;i++)
  51. {
  52. printf("Enter the index of vertex 1:n");
  53. scanf("%d",&ver1);
  54. printf("Enter the index of vertex 2:n");
  55. scanf("%d",&ver2);
  56. if(ver1>g->verNum-1||ver2>g->verNum-1) exit(-1);
  57. g->matrix[ver1][ver2].adj=1;
  58. g->matrix[ver2][ver1].adj=1;
  59. }
  60. }
  61. void printMatrix(graph *g)
  62. {
  63. if(!g||!g->matrix||!g->verList) exit(-1);
  64. printf("Print the adjacency matrix:");
  65. for(int i=0;i<g->verNum;i++)
  66. {
  67. for(int j=0;j<g->verNum;j++)
  68. {
  69. printf("%d ",g->matrix[i][j].adj);
  70. }
  71. printf("n");
  72. }
  73. }
  74. int main() {
  75. graph *g=createGraph(5);
  76. verNode **matrix =createMatrix(g);
  77. g->matrix=matrix;
  78. addEdge(g,7);
  79.  
  80. return 0;
  81. }
  82.  
  83. g->matrix = malloc(sizeof(int*) * g->verNum * g->verNum);
  84.  
  85. g->matrix = malloc(g->verNum * sizeof(*g->matrix));
  86.  
  87. for (int i = 0; i < verNum; i++) {
  88. g->matrix[i] = calloc(g->verNum, sizeof(*g->matrix[i]));
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement