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