C언어 그래프 (인접행렬)

1 개념[편집]

  • 인접행렬 방식으로 그래프 구현
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct { 
	int vertexCount; 
	int **matrix; 
} graphType;

graphType *createGraph(int vertexCount)
{
	int i;

	graphType *graph = (graphType *)malloc(sizeof(graphType) * vertexCount);
	graph->matrix = (int **)malloc(sizeof(int *) * vertexCount);
	
	graph->vertexCount = vertexCount;
	
	for (i = 0; i < vertexCount; i++) {
		graph->matrix[i] = (int *)malloc(sizeof(int) * vertexCount);
		memset(graph->matrix[i], 0, sizeof(int) * vertexCount);
	}
	return graph;
}

void addEdge(graphType *graph, int start, int goal)
{
	graph->matrix[start - 1][goal - 1] = 1;	
}

void printGraph(graphType *graph)
{
	int i, j;

	for (i = 0; i < graph->vertexCount; i++) {
		printf("start %d ->", i);
		for (j = 0; j < graph->vertexCount; j++) {
			printf("%d ", graph->matrix[i][j]);
		}
		printf("\n");
	}
}

{
	graphType *graph;
	graph = createGraph(5);

	addEdge(graph, 1, 2);
	addEdge(graph, 1, 3);
	addEdge(graph, 1, 4);
	addEdge(graph, 1, 5);
	addEdge(graph, 2, 3);
	addEdge(graph, 2, 5);
	addEdge(graph, 5, 4);

	printGraph(graph);

	return 0;
}

2 같이 보기[편집]