Cod sursa(job #2740440)

Utilizator radu01Toader Radu Marian radu01 Data 12 aprilie 2021 23:07:50
Problema Parcurgere DFS - componente conexe Scor 5
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.78 kb
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct vertex {
	int name;
	struct vertex** neighbors;
	int numNeighbors;
} vertex;

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

void dfs_vertex(graphVertex graph, int currentNode, int* visited)
{
	visited[currentNode] = 1;
	for (int j = 0; j < graph.nodes[currentNode].numNeighbors; j++) {
		if (visited[graph.nodes[currentNode].neighbors[j]->name] == 0) {
			dfs_vertex(graph, graph.nodes[currentNode].neighbors[j]->name, visited);
		}
	}
}

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", &(graph.numNodes), &(graph.numEdges));
	graph.nodes = (vertex*)malloc(sizeof(vertex) * graph.numNodes);
	if (graph.nodes == NULL)
		return graph;
	for (int i = 0; i < graph.numNodes; i++) {
		graph.nodes[i].name = i;
		graph.nodes[i].numNeighbors = 0;
		graph.nodes[i].neighbors = NULL;
	}
	int left, right;
	for (int i = 0; i < graph.numEdges; i++) {
		fscanf(f, "%d %d", &left, &right);
		graph.nodes[left].numNeighbors++;
		graph.nodes[left].neighbors = (vertex**)realloc(graph.nodes[left].neighbors, sizeof(vertex*) * graph.nodes[left].numNeighbors);
		graph.nodes[left].neighbors[graph.nodes[left].numNeighbors - 1] = &graph.nodes[right];
	}
	fclose(f);
	return graph;
}

int main()
{
	graphVertex graphV = readGraphVertex("dfs.in");

	int visited[100001] = {0};
	int count = 0;

	for (int i = 0; i < graphV.numNodes; i++) {
		if (visited[i] == 0) {
			count++;
			dfs_vertex(graphV, i, visited);
		}
	}

	FILE* f = fopen("dfs.out", "w");
	fprintf(f, "%d", count);
	fclose(f);

	return 0;
}