C언어 그래프 구현

John Jeong (토론 | 기여)님의 2017년 5월 19일 (금) 00:21 판 (→‎개념)

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 같이 보기

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}