Cod sursa(job #2741857)

Utilizator dragossandu38Sandu Dragos dragossandu38 Data 19 aprilie 2021 17:27:24
Problema BFS - Parcurgere in latime Scor 80
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.91 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;
	vertex* nodes;
} graphVertex;
#define SIZE 100002

graphVertex readGraphVertex(const char* fileName, int* s)
{
	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), &(*s));
	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 e1, e2;
	for (int i = 1; i <= graph.numEdges; i++) {
		fscanf(f, "%d %d", &e1, &e2);
		graph.nodes[e1].numNeighbors++;
		graph.nodes[e1].neighbors = (vertex*)realloc(graph.nodes[e1].neighbors, sizeof(vertex) * (graph.nodes[e1].numNeighbors + 1));
		graph.nodes[e1].neighbors[graph.nodes[e1].numNeighbors].name = e2;
	}

	fclose(f);
	return graph;
}
int coada[SIZE];
void bfs_search(graphVertex graph, int startNode)
{
	int left = 0, right = 0;
	coada[right++] = startNode;
	graph.nodes[startNode].weights = 0;
	while (left <= right) {
		int node = coada[left++];
		for (int i = 1; i <= graph.nodes[node].numNeighbors; i++) {
			if (graph.nodes[graph.nodes[node].neighbors[i].name].weights == -1) {
				coada[right++] = graph.nodes[node].neighbors[i].name;
				graph.nodes[graph.nodes[node].neighbors[i].name].weights = graph.nodes[node].weights + 1;
			}
		}
	}
}

int main()
{
	int s;
	graphVertex graph = readGraphVertex("bfs.in", &s);
	bfs_search(graph, s);
	FILE* f = fopen("bfs.out", "w");
	if (f == NULL)
		return;
	for (int i = 1; i <= graph.numNodes; i++) {
		fprintf(f, "%d ", graph.nodes[i].weights);
	}
	fclose(f);
}