You are on page 1of 25

Министерство Образования и Исследований Республики Молдова

Технический Университет Молдовы Департамент Физики

Отчет
по лабораторной работе Nr.1.
по Дискретной математике

Тема: Хранение графов в памяти ЭВМ.

Выполнил ст.гр. TI-239 Lazarev Nichita

Кишинев – 2023
Цель работы:
1. Освоение и изучение способов задания графов: матрица
инцидентности, матрица смежности, список смежности.
2. Разработка процедур преобразования видов хранения графов с
выдачей результатов на дисплей.
Задание
1. Разработать процедуры ввода графа в виде матрицы
инцидентности, матрицы смежности и списка смежности с
возможностью корректировки введенных данных.
2.Разработать процедуры преобразования различных форм
хранения графа:
-- из матрицы смежности в список смежности и обратно;
-- из матрицы инцидентности в список смежности и обратно;
3. Используя указанные выше процедуры, получить
программу, выполняющую следующие функции:
--ввод графа в любой из трех форм представления (по требованию
пользователя);
--хранение введенного графа в памяти ЭВМ в виде списка
смежности;
-- вывод информации о графе в любом из трех видов (также по
требованию пользователя) на дисплей;

Код программы:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

typedef struct sNode


{
int vertex;
struct sNode *next;
} tNode;

typedef struct sGraph


{
int vertices;
int edges;
int **adjacencyMatrix;
int **incidenceMatrix;
tNode **adjacencyList;
} tGraph;

tGraph *createGraph(int vertices, int edges)


{
tGraph *graph = malloc(sizeof(tGraph));
graph->vertices = vertices;
graph->edges = edges;

graph->adjacencyMatrix = malloc((vertices + 1) * sizeof(int *));


for (int i = 1; i <= vertices; i++)
{
graph->adjacencyMatrix[i] = malloc((vertices + 1) * sizeof(int));
for (int j = 1; j <= vertices; j++)
{
graph->adjacencyMatrix[i][j] = 0;
}
}

graph->incidenceMatrix = malloc((edges + 1) * sizeof(int *));


for (int i = 1; i <= edges; i++)
{
graph->incidenceMatrix[i] = malloc((vertices + 1) * sizeof(int));
for (int j = 1; j <= vertices; j++)
{
graph->incidenceMatrix[i][j] = 0;
}
}

graph->adjacencyList = malloc(sizeof(tNode));
for (int i = 1; i <= vertices; i++)
{
graph->adjacencyList[i] = NULL;
}
return graph;
}

void addEdgeToList(tGraph *graph, int start, int end)


{
tNode *newNode = malloc(sizeof(tNode));
newNode->vertex = end;
newNode->next = graph->adjacencyList[start];
graph->adjacencyList[start] = newNode;
}

void addEdgeToAdjacencyMatrix(tGraph *graph, int start, int end)


{
if (start != end)
{
graph->adjacencyMatrix[start][end] = 1;
}
if (start == end)
{
graph->adjacencyMatrix[start][end] = 2;
}
}

void addEdgeToIncidenceMatrix(tGraph *graph, int start, int end)


{
static int staticValue = 1;
for (int i = 1; i <= graph->vertices; i++)
{
if (i == start)
{
graph->incidenceMatrix[staticValue][i] = -1;
}
else if (i == end)
{
graph->incidenceMatrix[staticValue][i] = 1;
}
else if (start == end)
{
graph->incidenceMatrix[staticValue][start] = 2;
}
else
{
graph->incidenceMatrix[staticValue][i] = 0;
}
}
staticValue++;
}

void printAdjacencyList(tGraph *graph)


{
printf("\n");
for (int i = 1; i <= graph->vertices; i++)
{
tNode *current = graph->adjacencyList[i];
printf("%d: ", i);
while (current != NULL)
{
printf("%d", current->vertex);
if (current->next != NULL)
{
printf(",");
}
current = current->next;
}
printf("\n");
}
}

void printAdjacencyMatrix(tGraph *graph)


{
printf("\n");
for (int i = 1; i <= graph->vertices; i++)
{
for (int j = 1; j <= graph->vertices; j++)
{
printf("%d ", graph->adjacencyMatrix[i][j]);
}
printf("\n");
}
}

void printIncidenceMatrix(tGraph *graph)


{
printf("\n");
for (int i = 1; i <= graph->edges; i++)
{
for (int j = 1; j <= graph->vertices; j++)
{
printf("%d ", graph->incidenceMatrix[i][j]);
}
printf("\n");
}
}

void convertListToAdjMatrix(tGraph *graph)


{
for (int i = 1; i <= graph->vertices; i++)
{
for (int j = 1; j <= graph->vertices; j++)
{
graph->adjacencyMatrix[i][j] = 0;
}
}

for (int i = 1; i <= graph->vertices; i++)


{
tNode *convert = graph->adjacencyList[i];
while (convert != NULL)
{
if (graph->adjacencyMatrix[i] != graph-
>adjacencyMatrix[convert->vertex])
{
graph->adjacencyMatrix[i][convert->vertex] = 1;
convert = convert->next;
}
else if (graph->adjacencyMatrix[i] == graph-
>adjacencyMatrix[convert->vertex])
{
graph->adjacencyMatrix[i][convert->vertex] = 2;
convert = convert->next;
}
}
}
}

void convertListToIncMatrix(tGraph *graph)


{
for (int i = 1; i <= graph->edges; i++)
{
for (int j = 1; j <= graph->vertices; j++)
{
graph->incidenceMatrix[i][j] = 0;
}
}
int jincrement = 1;
for (int i = 1; i <= graph->vertices; i++)
{
tNode *convert = graph->adjacencyList[i];
while (convert != NULL)
{
if (jincrement <= graph->edges)
{
if (graph->incidenceMatrix[i] != graph-
>incidenceMatrix[convert->vertex])
{

graph->incidenceMatrix[jincrement][i] = -1;
graph->incidenceMatrix[jincrement][convert->vertex] = 1;
}
else if (graph->incidenceMatrix[i] == graph-
>incidenceMatrix[convert->vertex])
{
graph->incidenceMatrix[jincrement][i] = 0;
graph->incidenceMatrix[jincrement][convert->vertex] = 2;
}
}
convert = convert->next;
jincrement++;
}
}
}

void convertAdjacencyMatrixToList(tGraph *graph)


{
graph->adjacencyList = malloc((graph->vertices + 1) * sizeof(tNode
*));

for (int i = 1; i <= graph->vertices; i++)


{
graph->adjacencyList[i] = NULL;
}

for (int i = 1; i <= graph->vertices; i++)


{
for (int j = 1; j <= graph->vertices; j++)
{
if (graph->adjacencyMatrix[i][j] == 1)
{
tNode *newNode = malloc(sizeof(tNode));
newNode->vertex = j;
newNode->next = graph->adjacencyList[i];
graph->adjacencyList[i] = newNode;
}
if (graph->adjacencyMatrix[i][j] == 2)
{
tNode *tmp = malloc(sizeof(tNode));
tmp->vertex = j;
tmp->next = graph->adjacencyList[i];
graph->adjacencyList[i] = tmp;
}
}
}
}

void convertIncedenceMatrixToList(tGraph *graph)


{
graph->adjacencyList = malloc((graph->vertices + 1) * sizeof(tNode
*));
for (int i = 1; i <= graph->vertices; i++)
{
graph->adjacencyList[i] = NULL;
}
for (int i = 1; i <= graph->edges; i++)
{
int start = 0;
int end = 0;
for (int j = 1; j <= graph->vertices; j++)
{
if (graph->incidenceMatrix[i][j] == -1)
{
start = j;
}
else if (graph->incidenceMatrix[i][j] == 1)
{
end = j;
}
if (graph->incidenceMatrix[i][j] == 2)
{
start = j;
end = j;
}
}
tNode *newNode = malloc(sizeof(tNode));
newNode->vertex = end;
newNode->next = graph->adjacencyList[start];
graph->adjacencyList[start] = newNode;
}
}

void dataCorrection1(tGraph *graph, int edges)


{
printf("Enter edges in format from start point to end point:\n");

for (int i = 1; i <= graph->vertices; i++)


{
graph->adjacencyList[i] = NULL;
}

for (int i = 1; i <= edges; i++)


{
int start, end;
scanf("%d %d", &start, &end);
addEdgeToList(graph, start, end);
}
}

void dataCorrection2(tGraph *graph, int edges)


{
printf("Enter edges in format from start point to end point:\n");

for (int i = 1; i <= graph->vertices; i++)


{
for (int j = 1; j <= graph->vertices; j++)
{
graph->adjacencyMatrix[i][j] = 0;
}
}

for (int i = 1; i <= edges; i++)


{
int start, end;
scanf("%d %d", &start, &end);
addEdgeToAdjacencyMatrix(graph, start, end);
}
}

void dataCorrection3(tGraph *graph, int edges)


{
printf("Enter edges in format from start point to end point:\n");
for (int i = 1; i <= graph->edges; i++)
{
for (int j = 1; j <= graph->vertices; j++)
{
graph->incidenceMatrix[i][j] = 0;
}
}

for (int i = 1; i <= edges; i++)


{
int start, end;
scanf("%d %d", &start, &end);
addEdgeToIncidenceMatrix(graph, start, end);
}
}

int main(int argc, char const *argv[])


{

int vertices, edges;


printf("Enter number of vertices: ");
scanf("%d", &vertices);
printf("Enter number of edges: ");
scanf("%d", &edges);
tGraph *graph = createGraph(vertices, edges);
int start;
int end;

printf("Choose an option:\n");
printf("1.Add and print adjaceent list.\n");
printf("2.Add and print adjacent Matrix.\n");
printf("3.Add and print incidence Matrix.\n");

int option;
scanf("%d", &option);

do
{

switch (option)
{
case 1:
printf("Enter edges in format from start point to end point:\n");
for (int i = 0; i < edges; i++)
{
int start, end;
scanf("%d %d", &start, &end);
addEdgeToList(graph, start, end);
}

printAdjacencyList(graph);
step:
printf("Choose next action:\n");
printf("1.Convert adjacency List into adjacency Matrix.\n");
printf("2.Convert adjacency List into incidence Matrix.\n");
printf("3.Edit input.\n");
printf("4.Enter '0' to stop\n");
int option1;
scanf("%d", &option1);
switch (option1)
{
case 1:
convertListToAdjMatrix(graph);
printAdjacencyMatrix(graph);
break;
case 2:
convertListToIncMatrix(graph);
printIncidenceMatrix(graph);
break;
case 3:
dataCorrection1(graph, edges);
printAdjacencyList(graph);
goto step;
break;
case 0:
return 0;
}
break;
case 2:
printf("Enter edges in format from start point to end point:\n");
for (int i = 0; i < edges; i++)
{
int start, end;
scanf("%d %d", &start, &end);
addEdgeToAdjacencyMatrix(graph, start, end);
}

printAdjacencyMatrix(graph);
step2:
printf("Choose next action:\n");
printf("1.Convert adjacency Matrix into adjacency List.\n");
printf("2.Edit input\n");
printf("3.Enter '0' to stop\n");
int option2;
scanf("%d", &option2);
switch (option2)
{
case 1:
convertAdjacencyMatrixToList(graph);
printAdjacencyList(graph);
break;
case 2:
dataCorrection2(graph, edges);
printAdjacencyMatrix(graph);
goto step2;
break;
case 0:
return 0;
}
break;
case 3:
printf("Enter edges in format from start point to end point:\n");
for (int i = 0; i < edges; i++)
{
int start, end;
scanf("%d %d", &start, &end);
addEdgeToIncidenceMatrix(graph, start, end);
}

printIncidenceMatrix(graph);
// step3:
printf("Choose next action:\n");
printf("1.Convert incedence Matrix into adjacency List.\n");
printf("2.Edit input\n");
printf("3.Enter '0' to stop\n");
int option3;
scanf("%d", &option3);
switch (option3)
{
case 1:
convertIncedenceMatrixToList(graph);
printAdjacencyList(graph);
break;
case 2:
dataCorrection3(graph, edges);
printIncidenceMatrix(graph);
// goto step3;
break;
case 0:
return 0;
}
break;
}
} while (option != 0);
return 0;
}
///Пример ввода:

Enter number of vertices: 6

Enter number of edges: 9

Choose an option:

1.Add and print adjacent list.

2.Add and print adjacent Matrix.

3.Add and print incidence Matrix.

1.Add and print adjacent List

Enter edges in format from start point to end point: 1 2 1 5 1 6 2 3 3 5 4 3 4 5 5 2 6 4

1.Convert adjacency List into adjacency Matrix


2.Convert adjacency List into incidence Matrix

2.Add and print adjacency Matrix

1.Convert adjacency Matrix into adjacency List

3.Add and print incidence Matrix


1.Convert incidence Matrix into adjacency List

You might also like