Cod sursa(job #2741921)

Utilizator dragossandu38Sandu Dragos dragossandu38 Data 19 aprilie 2021 19:01:51
Problema Parcurgere DFS - componente conexe Scor 100
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.85 kb
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

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

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

int visited[100001];
void dfs(graphVertex graph, int currentNode)
{
	visited[currentNode] = 1;
	for (int i = 1; i <= graph.nodes[currentNode].numNeighbors; i++) {
		if (visited[graph.nodes[currentNode].neighbors[i]] == 0)
			dfs(graph, graph.nodes[currentNode].neighbors[i]);
	}
}
int N, M;
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 = 1; i <= graph.numNodes; i++) {
		graph.nodes[i].name = i;
		graph.nodes[i].numNeighbors = 0;
		graph.nodes[i].neighbors = NULL;
	}
	int e1, e2;
	for (int i = 1; i <= graph.numEdges; i++) {
		fscanf(f, "%d %d", &e1, &e2);
		graph.nodes[e1].numNeighbors++;
		graph.nodes[e1].neighbors = (int*)realloc(graph.nodes[e1].neighbors, sizeof(int) * (graph.nodes[e1].numNeighbors + 1));
		graph.nodes[e1].neighbors[graph.nodes[e1].numNeighbors] = e2;

		graph.nodes[e2].numNeighbors++;
		graph.nodes[e2].neighbors = (int*)realloc(graph.nodes[e2].neighbors, sizeof(int) * (graph.nodes[e2].numNeighbors + 1));
		graph.nodes[e2].neighbors[graph.nodes[e2].numNeighbors] = e1;
	}

	fclose(f);
	return graph;
}

int main()
{
	int count = 0;

	graphVertex graph = readGraphVertex("dfs.in");
	for (int i = 1; i <= graph.numNodes; i++) {
		if (visited[graph.nodes[i].name] == 0) {
			count++;
			dfs(graph, graph.nodes[i].name);
		}
	}
	FILE* f = fopen("dfs.out", "w");

	fprintf(f, "%i", count);
	fclose(f);
	return 0;
}