작심 365
[c언어] 인접행렬을 이용해서 그래프 구현 본문
무방향 그래프를 인접행렬을 이용해서 표현.
편의를 위해서 정점의 최대 갯수를 제한.

#include<stdio.h>
#include<stdlib.h>
#define MAX_VERTICES 50 // 최대 정점 갯수 제한
typedef struct GraphType { // 그래프
int n; // 정점 개수
int adj_mat[MAX_VERTICES][MAX_VERTICES];
} GraphType;
void graph_init(GraphType* g) {
int r, c; // 행,열
g->n = 0;
for (r = 0; r < MAX_VERTICES; r++)
for (c = 0; c < MAX_VERTICES; c++)
g->adj_mat[r][c] = 0; // 배열의 모든 값을 0으로 초기화
}
void insert_edge(GraphType* g, int start, int end) {
if (start > g->n || end > g->n) {
fprintf(stderr, "그래프: 정점 번호 오류\n");
return;
}
// 행렬에 간선 정보 저장.
g->adj_mat[start-1][end-1]=1;
g->adj_mat[end-1][start-1] = 1;
}
void print_graph(GraphType* g) {
int max = g->n;
for (int i = 0; i < max; i++) {
for (int j = 0; j < max; j++) {
printf("%d ", g->adj_mat[i][j]);
}
printf("\n");
}
}
int main() {
GraphType* g = (GraphType*)malloc(sizeof(GraphType));
graph_init(g); // 배열 초기화
g->n = 5; // 정점의 갯수가 5개인 그래프
// 그래프에 간선 삽입
insert_edge(g, 1, 2);
insert_edge(g, 2, 4);
insert_edge(g, 2, 5);
insert_edge(g, 2, 3);
insert_edge(g, 3, 4);
// 그래프 출력
print_graph(g);
return 0;
}
결과

'자료구조' 카테고리의 다른 글
| [c언어] linked list 로 stack 구현 (0) | 2022.06.12 |
|---|
Comments