fork download
  1. #include <stdio.h>
  2.  
  3. #define MAX_VERTEX 50
  4.  
  5. typedef struct graphType {
  6. int n;
  7. int adjMatrix[MAX_VERTEX][MAX_VERTEX];
  8. } graphType;
  9.  
  10. void createGraph(graphType* g) {
  11. int i, j;
  12. g->n = 0;
  13. for (i = 0; i < MAX_VERTEX; i++) {
  14. for (j = 0; j < MAX_VERTEX; j++) {
  15. g->adjMatrix[i][j] = 0;
  16. }
  17. }
  18. }
  19.  
  20. void insertVertex(graphType* g, int v) {
  21. if (((g->n) + 1) > MAX_VERTEX) {
  22. printf("\n그래프 정점의 개수를 초과했습니다.");
  23. return;
  24. }
  25. g->n++;
  26. }
  27.  
  28. void insertEdge(graphType* g, int u, int v) {
  29. if (u < 0 || u >= g->n || v < 0 || v >= g->n) {
  30. printf("\n간선 삽입 오류: 정점 번호가 범위를 벗어났습니다.");
  31. return;
  32. }
  33. g->adjMatrix[u][v] = 1;
  34. g->adjMatrix[v][u] = 1; // 무방향 그래프의 경우
  35. }
  36.  
  37. void printAdjMatrix(graphType* g) {
  38. int i, j;
  39. printf("\n인접 행렬:\n");
  40. for (i = 0; i < g->n; i++) {
  41. for (j = 0; j < g->n; j++) {
  42. printf(" %d", g->adjMatrix[i][j]);
  43. }
  44. printf("\n");
  45. }
  46. }
  47.  
  48. int main() {
  49. graphType g;
  50. createGraph(&g);
  51.  
  52. insertVertex(&g, 0);
  53. insertVertex(&g, 1);
  54. insertVertex(&g, 2);
  55.  
  56. insertEdge(&g, 0, 1);
  57. insertEdge(&g, 1, 2);
  58. insertEdge(&g, 0, 2);
  59.  
  60. printAdjMatrix(&g);
  61.  
  62. return 0;
  63. }
  64.  
Success #stdin #stdout 0s 5248KB
stdin
Standard input is empty
stdout
인접 행렬:
 0 1 1
 1 0 1
 1 1 0