안녕하세요. 언제나 휴일에 언휴예요.
이번에는 그래프를 인접행렬로 구현하는 실습이예요.
/* https://ehpub.co.kr
언제나 C언어 예제 Center
방향성 없는 그래프
*/
#include
#include
#include
typedef struct {
int vn;//정점 개수
int** matrix;//인접행렬
}Graph;
Graph *MakeGraph();
void ViewNeighbors(Graph* graph);
void DeleteGraph(Graph* graph);
int main()
{
Graph* graph;
graph = MakeGraph();
ViewNeighbors(graph);
DeleteGraph(graph);
return 0;
}
Graph* NewGraph(int max_vertex);
void AddEdge(Graph* graph, int start, int goal);
Graph* MakeGraph()
{
Graph* graph;
graph = NewGraph(9);
AddEdge(graph, 0, 1);
AddEdge(graph, 0, 2);
AddEdge(graph, 1, 2);
AddEdge(graph, 1, 3);
AddEdge(graph, 2, 4);
AddEdge(graph, 3, 6);
AddEdge(graph, 4, 5);
AddEdge(graph, 4, 6);
AddEdge(graph, 4, 7);
AddEdge(graph, 6, 8);
return graph;
}
Graph* NewGraph(int max_vertex)
{
int i = 0;
Graph* graph = (Graph*)malloc(sizeof(Graph));
graph->vn = max_vertex;
graph->matrix = (int**)malloc(sizeof(int*) * max_vertex);
for (int i = 0; i < max_vertex; i++)
{
graph->matrix[i] = (int*)malloc(sizeof(int) * max_vertex);
memset(graph->matrix[i], 0, sizeof(int) * max_vertex);
}
return graph;
}
void AddEdge(Graph* graph, int start, int goal)
{
graph->matrix[start][goal] = 1;
graph->matrix[goal][start] = 1;
}
void ViewNeighbor(Graph* graph,int vt);
void ViewNeighbors(Graph* graph)
{
int i;
printf("==== 이웃 정점 =====\n");
for (i = 0; i < graph->vn; i++)
{
printf("%d의 이웃: ", i);
ViewNeighbor(graph, i);
printf("\n");
}
}
void ViewNeighbor(Graph* graph, int vt)
{
int i = 0;
for (i = 0; i < graph->vn; i++)
{
if (graph->matrix[vt][i])
{
printf("%d ", i);
}
}
}
void DeleteGraph(Graph* graph)
{
int i = 0;
for (i = 0; i < graph->vn; i++)
{
free(graph->matrix[i]);
}
free(graph->matrix);
free(graph);
}