Cod sursa(job #2741528)

Utilizator stefan.lascuzeanuLascuzeanu Stefan-Andrei stefan.lascuzeanu Data 16 aprilie 2021 12:30:01
Problema Parcurgere DFS - componente conexe Scor 15
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.84 kb
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//POINTERS/VERTEX
typedef struct vertex {
	int name;
	struct vertex** neighbors;
	int numNeighbors;
} vertex;

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

int covered = 0;

void dfs(graphVertex graph, int here)
{
	if (graph.nodes[here].name != -1) {
		graph.nodes[here].name = -1;
		for (int k = 0; k < graph.nodes[here].numNeighbors; k++) {
			if (graph.nodes[here].neighbors[k]->name != -1) {
				dfs(graph, graph.nodes[here].neighbors[k]->name);
			}
		}
	}
}

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\n", &(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 a, b;
	for (int i = 0; i < graph.numEdges; i++) {
		fscanf(f, "%i %i", &a, &b);
		a--;
		b--;
		if (graph.nodes[a].numNeighbors == 0) {
			graph.nodes[a].neighbors = (vertex**)malloc(sizeof(vertex*));
		}
		graph.nodes[a].neighbors = (vertex**)realloc(graph.nodes[a].neighbors, sizeof(vertex**) * (++graph.nodes[a].numNeighbors));
		graph.nodes[a].neighbors[graph.nodes[a].numNeighbors - 1] = &(graph.nodes[b]);
		//&(graph.nodes[b]);
	}
	fclose(f);
	return graph;
}

int main()
{
	graphVertex graphV = readGraphVertex("dfs.in");
	int ct = 0;
	for (int i = 0; i < graphV.numNodes; i++) {
		if (graphV.nodes[i].name != -1) {
			dfs(graphV, i);
			ct++;
		}
	}
	FILE* o = fopen("dfs.out", "w");
	fprintf(o, "%d", ct);
	fclose(o);
	return 0;
}