Cod sursa(job #2741456)

Utilizator IoanaV20Voica Ioana IoanaV20 Data 15 aprilie 2021 23:36:08
Problema Parcurgere DFS - componente conexe Scor 5
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.95 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;

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 + 1));
	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 x, y;
	for (int i = 0; i < graph.numEdges; i++) {  //
		fscanf(f, "%d%d", &x, &y);

		graph.nodes[x].numNeighbors++;
		graph.nodes[x].neighbors = (vertex**)realloc(graph.nodes[x].neighbors, graph.nodes[x].numNeighbors * sizeof(vertex*));
		graph.nodes[x].neighbors[graph.nodes[x].numNeighbors - 1] = &(graph.nodes[y]);
		graph.nodes[y].numNeighbors++;
		graph.nodes[y].neighbors = (vertex**)realloc(graph.nodes[y].neighbors, graph.nodes[y].numNeighbors * sizeof(vertex*));
		graph.nodes[y].neighbors[graph.nodes[y].numNeighbors - 1] = &(graph.nodes[x]);
	}
	fclose(f);
	return graph;
}

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

int main(int argc, char** argv)
{
	graphVertex graph = readGraphVertex("dfs.in");
	int* visited = (int*)calloc((graph.numNodes + 1), sizeof(int));
	int nr = 0;
	for (int i = 1; i <= graph.numNodes; i++)
		if (!visited[i]) {
			nr++;
			dfs_vertex(graph, i, visited);
		}
	FILE* g = fopen("dfs.out", "w");
	fprintf(g, "%d", nr);
	fclose(g);
}