Вы находитесь на странице: 1из 6

Universitatea Techinca a Moldovei

Departamentul Ingenerie Software Automatice

Отчёт
О выполнении лабораторной работы №3
По Дискретной Математике.
Тема: Использование структур данных для поиска на
деревьях и графах. Алгоритм поиска в ширину.

Выполнил: Шокот Андрей


Проверила: Т. Тихолаз

Кишинёв, 2024.
Теоретическая справка:
Список – конечное множество упорядоченных элементов одинакового типа.
Количество элементов в списке называется его длиной, может динамически
изменяться. Список, в котором нет элементов называется пустым списком.

Очередь – используется для реализации обработки элементов списка, где


элементы списка удаляются из него в порядке их включения в список (т.е. по
принципу "Первым пришел - первым ушел").

Дерево – ацикличный граф. Вершины, имеющие смежные элементы


называются отцами, вершины, с которыми они смежные – сыновьями,
вершины без смежных элементов – листья. Корень дерева – вершина, которая
не является смежной ни для одной вершины.

Обход дерева в ширину – алгоритм обработки дерева, цель которого обойти


каждую вершину дерева, двигаясь, в первую очередь, по уровням дерева
слева направо. Для этого алгоритма используется 2 очереди, в которых
хранятся текущие данные, и список, в котором будет храниться результат
работы алгоритма.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX_VERTICES 100

struct Node {
int data;
struct Node* next;
};

struct Queue {
int order[MAX_VERTICES];
int front;
int last;
};

struct Node* createNode(int data) {


struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}

void addEdge(struct Node** adjLists, int start, int end) {


struct Node* newNode = createNode(end);
if (adjLists[start] == NULL) {
adjLists[start] = newNode;
} else {
struct Node* current = adjLists[start];
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}

void printGraph(struct Node** adjLists, int numVertices) {


printf("Adjacency List:\n");
for (int i = 1; i <= numVertices; i++) {
printf("%d - ", i);
struct Node* current = adjLists[i];
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("0\n");
}
}

void push(struct Queue* q, int value) {


q->last++;
q->order[q->last] = value;
}

int pop(struct Queue* q) {


int trmd = q->order[q->front];
q->front++;
return trmd;
}

bool empty(struct Queue* q) {


return q->front > q->last;
}

void checkAndAddMissingVertices( bool* visited, int numVertices) {


for (int i = 1; i <= numVertices; ++i) {
if (!visited[i]) {
visited[i] = true;
printf(" %d", i);
}
}
}

void bfs(struct Node** adjLists, int startVertex, bool* visited, int


numVertices) {
struct Queue* q = (struct Queue*)malloc(sizeof(struct Queue));
q->front = 0;
q->last = -1;
visited[startVertex] = true;
push(q, startVertex);
while (!empty(q)) {
int currentVertex = pop(q);
printf("%d ", currentVertex);
struct Node* current = adjLists[currentVertex];
while (current != NULL) {
int adjVertex = current->data;
if (!visited[adjVertex]) {
push(q, adjVertex);
visited[adjVertex] = true;
}
current = current->next;
}
}
checkAndAddMissingVertices( visited, numVertices);
free(q);
}

int main() {
int numVertices;
printf("Enter the number of vertices: ");
scanf("%d", &numVertices);

struct Node** adjLists = (struct Node**)malloc((numVertices+1) *


sizeof(struct Node*));
for (int i = 0; i <= numVertices; i++) {
adjLists[i] = NULL;
}

printf("Enter your list:\n");


for (int i = 1; i <= numVertices; i++) {
int vertex, adjacentVertex;
printf("%d - ", i);
do {
scanf("%d", &adjacentVertex);
if (adjacentVertex != 0)
addEdge(adjLists, i, adjacentVertex);
} while (adjacentVertex != 0);
}

printGraph(adjLists, numVertices);

bool* visited = (bool*)malloc((numVertices + 1) * sizeof(bool));


for (int i = 0; i <= numVertices; ++i) {
visited[i] = false;
}

int startVertex;
printf("Enter the start vertex for BFS: ");
scanf("%d", &startVertex);

printf("BFS traversal starting from vertex %d: ", startVertex);


bfs(adjLists, startVertex, visited,numVertices);
printf("\n");

return 0;
}

Вывод:
В ходе выполнения лабораторной работы, где применялись алгоритм поиска в ширину и
структура данных "очередь" на языке программирования C.
Изучены основные принципы работы алгоритма BFS, который обеспечивает обход графа по
уровням, начиная с заданной стартовой вершины.
Алгоритм BFS помогает находить кратчайшие пути от стартовой вершины до всех остальных
вершин в невзвешенном графе. Поняты преимущества использования очереди в алгоритме BFS,
где она обеспечивает сохранение порядка посещения вершин.

Вам также может понравиться