Cod sursa(job #2740500)

Utilizator CorbuIonutCorbu Ionut-Daniel CorbuIonut Data 13 aprilie 2021 13:16:03
Problema Parcurgere DFS - componente conexe Scor 15
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.55 kb
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

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

	fscanf(f, "%i%i", &NumberOfNodes, &NumberOfEdges);
	graphVertex* nodes = (graphVertex*)malloc((NumberOfNodes + 1) * sizeof(graphVertex));
	if (nodes == NULL)
		return nodes;
	for (int i = 1; i <= NumberOfNodes; 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 < NumberOfEdges; i++) {
		fscanf(f, "\n%i%i", &stanga, &dreapta);
		nodes[stanga].numNeighbours++;
		nodes[stanga].neighbours = (int*)realloc(nodes[stanga].neighbours, (nodes[stanga].numNeighbours + 1) * sizeof(int));
		nodes[stanga].neighbours[nodes[stanga].numNeighbours - 1] = dreapta;
	}
	fclose(f);
	return nodes;
}
void dfs(graphVertex* graph, int root)
{
	for (int i = 0; i < graph[root].numNeighbours; i++)
		if (graph[graph[root].neighbours[i]].weights == -1) {
			graph[graph[root].neighbours[i]].weights = graph[root].weights;
			dfs(graph, graph[root].neighbours[i]);
		}
}
int main()
{
	graphVertex* graph = readGraphVertex("dfs.in");
	int nrconexe = 1;
	for (int j = 1; j <= NumberOfNodes; j++) {
		if (graph[j].weights == -1) {
			graph[j].weights = nrconexe;
			dfs(graph, j);
			nrconexe++;
		}
	}
	FILE* f = fopen("dfs.out", "w");
	fprintf(f, "%d", nrconexe - 1);
	fclose(f);
}