Cod sursa(job #2741168)

Utilizator ioana.mistric.euIoana Mistric ioana.mistric.eu Data 15 aprilie 2021 17:21:50
Problema BFS - Parcurgere in latime Scor 100
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.71 kb
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct graphVertex {
	int numNeighbours;
	int* neighbours;
	int name;
	int weights;
} graphVertex;
int noduri, muchii, r;
graphVertex* readGraphVertex(const char* fileName)
{
	FILE* f = fopen(fileName, "r");
	if (f == NULL)
		return NULL;

	fscanf(f, "%i%i%i", &noduri, &muchii, &r);
	graphVertex* nodes = (graphVertex*)malloc((noduri + 1) * sizeof(graphVertex));
	if (nodes == NULL)
		return nodes;
	for (int i = 1; i <= noduri; i++) {
		nodes[i].name = i;
		nodes[i].numNeighbours = 0;
		nodes[i].neighbours = NULL;
		nodes[i].weights = -1;
	}
	int stanga, dreapta;
	for (int i = 0; i < muchii; i++) {
		fscanf(f, "\n%i%i", &stanga, &dreapta);
		nodes[stanga].numNeighbours++;
		nodes[stanga].neighbours = (int*)realloc(nodes[stanga].neighbours, (nodes[stanga].numNeighbours) * sizeof(int));
		nodes[stanga].neighbours[nodes[stanga].numNeighbours - 1] = dreapta;
	}
	fclose(f);
	return nodes;
}
int queue[100001];
void bfs(graphVertex* graph, int startnode)
{
	graph[startnode].weights = 0;
	int nivel = 1;
	queue[nivel] = startnode;
	int limit = 1;
	while (limit <= nivel) {
		int value = queue[limit];
		limit++;
		for (int i = 0; i < graph[value].numNeighbours; i++)
			if (graph[graph[value].neighbours[i]].weights == -1) {
				nivel++;
				queue[nivel] = graph[graph[value].neighbours[i]].name;
				graph[graph[value].neighbours[i]].weights = 1 + graph[value].weights;
			}
	}
}
int main()
{
	graphVertex* graph = readGraphVertex("bfs.in");
	bfs(graph, r);
	FILE* f = fopen("bfs.out", "w");
	for (int i = 1; i <= noduri; i++)
		fprintf(f, "%i ", graph[i].weights);
	fclose(f);
}