Cod sursa(job #2741486)

Utilizator luca_raduluca 123 luca_radu Data 16 aprilie 2021 10:04:22
Problema Parcurgere DFS - componente conexe Scor 100
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.89 kb
#include <stdio.h>
#include <stdlib.h>
#define size 100005
int visited[size] = {0};
typedef struct vertex {
	int name;
	int numNeighbours;
	struct vertex** neighbours;
} vertex;

typedef struct GraphVertex {
	int numNodes;
	int numEdges;
	vertex* nodes;
} GraphVertex;

GraphVertex ReadFile()
{
	FILE* f = fopen("dfs.in", "r");
	GraphVertex graph;
	fscanf(f, "%d %d", &graph.numNodes, &graph.numEdges);
	graph.nodes = (vertex*)malloc(graph.numNodes * sizeof(vertex));

	for (int i = 0; i < graph.numNodes; i++) {
		graph.nodes[i].numNeighbours = 0;
		graph.nodes[i].neighbours = NULL;
		graph.nodes[i].name = i + 1;
	}
	int stanga, dreapta;
	int aux = graph.numEdges;

	while (aux) {
		fscanf(f, "%d %d", &stanga, &dreapta);
		graph.nodes[stanga - 1].neighbours = (vertex**)realloc(graph.nodes[stanga - 1].neighbours, (graph.nodes[stanga - 1].numNeighbours + 1) * sizeof(vertex*));
		graph.nodes[stanga - 1].neighbours[graph.nodes[stanga - 1].numNeighbours] = graph.nodes + (dreapta - 1);
		graph.nodes[dreapta - 1].neighbours = (vertex**)realloc(graph.nodes[dreapta - 1].neighbours, (graph.nodes[dreapta - 1].numNeighbours + 1) * sizeof(vertex*));
		graph.nodes[dreapta - 1].neighbours[graph.nodes[dreapta - 1].numNeighbours] = graph.nodes + (stanga - 1);
		graph.nodes[stanga - 1].numNeighbours++;
		graph.nodes[dreapta - 1].numNeighbours++;
		aux--;
	}

	fclose(f);
	return graph;
}
void DFS(GraphVertex graph, int currentnode)
{
	visited[currentnode] = 1;
	for (int i = 0; i < graph.nodes[currentnode].numNeighbours; i++) {
		if (!visited[graph.nodes[currentnode].neighbours[i]->name - 1])
			DFS(graph, graph.nodes[currentnode].neighbours[i]->name - 1);
	}
}
int main()
{
	GraphVertex graph = ReadFile();
	int componente = 0;
	for (int i = 0; i < graph.numNodes; i++) {
		if (!visited[i]) {
			DFS(graph, i);
			componente++;
		}
	}
	FILE* out = fopen("dfs.out", "w");
	fprintf(out, "%d", componente);
	fclose(out);

	return 0;
}