Cod sursa(job #2740477)

Utilizator CorbuIonutCorbu Ionut-Daniel CorbuIonut Data 13 aprilie 2021 11:36:50
Problema BFS - Parcurgere in latime Scor 20
Compilator c-64 Status done
Runda Arhiva educationala Marime 2.15 kb
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct vertex {
	int name;
	struct vertex** neighbors;
	int numNeighbors;
	int weights;
} vertex;

typedef struct graphVertex {
	int numNodes;
	int numEdges;
	int root;
	vertex* nodes;
} graphVertex;
graphVertex readGraphVertex(const char* fileName)
{
	graphVertex graph;
	graph.numEdges = 0;
	graph.numNodes = 0;
	FILE* f = fopen(fileName, "r");
	if (f == NULL)
		return graph;

	fscanf(f, "%i%i%i", &(graph.numNodes), &(graph.numEdges), &(graph.root));
	graph.nodes = (vertex*)malloc(sizeof(vertex) * (graph.numNodes + 1));
	if (graph.nodes == NULL)
		return graph;
	for (int i = 1; i <= graph.numNodes; i++) {
		graph.nodes[i].name = i;
		graph.nodes[i].numNeighbors = 0;
		graph.nodes[i].neighbors = NULL;
		graph.nodes[i].weights = -1;
	}
	int stanga, dreapta;
	for (int i = 0; i < graph.numEdges; i++) {
		fscanf(f, "\n%i%i", &stanga, &dreapta);
		if (graph.nodes[stanga].numNeighbors == 0)
			graph.nodes[stanga].neighbors = (vertex**)malloc(sizeof(vertex*));
		else
			graph.nodes[stanga].neighbors = (vertex**)realloc(graph.nodes[stanga].neighbors, (graph.nodes[stanga].numNeighbors + 1) * sizeof(vertex*));
		graph.nodes[stanga].neighbors[graph.nodes[stanga].numNeighbors] = (vertex*)malloc(sizeof(vertex));
		graph.nodes[stanga].neighbors[graph.nodes[stanga].numNeighbors] = &graph.nodes[dreapta];
		graph.nodes[stanga].numNeighbors++;
	}
	fclose(f);
	return graph;
}
int queue[100001];
int indexQueue = 0;
int headofqueue = 0;
void bfs(graphVertex graph, int startnode)
{
	graph.nodes[startnode].weights = 0;
	queue[indexQueue++] = startnode;
	while (indexQueue >= headofqueue) {
		int value = queue[indexQueue - 1];
		headofqueue++;
		for (int i = 0; i < graph.nodes[value].numNeighbors; i++)
			if (graph.nodes[value].neighbors[i]->weights == -1) {
				queue[indexQueue++] = graph.nodes[value].neighbors[i]->name;
				graph.nodes[value].neighbors[i]->weights = 1 + graph.nodes[value].weights;
			}
	}
}
int main()
{
	graphVertex graph = readGraphVertex("bfs.in");
	bfs(graph, graph.root);
	FILE* f = fopen("bfs.out", "w");
	for (int i = 1; i <= graph.numNodes; i++)
		fprintf(f, "%i ", graph.nodes[i].weights);
	fclose(f);
}