Cod sursa(job #2741181)

Utilizator ioana.mistric.euIoana Mistric ioana.mistric.eu Data 15 aprilie 2021 17:41:33
Problema Parcurgere DFS - componente conexe Scor 10
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.83 kb
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>

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

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

void dfs_pointers(graphVertex graph, int currentNode, int* ok)
{
	if (!ok[currentNode]) {
		ok[currentNode] = 1;
		for (int i = 0; i < graph.nodes[currentNode].numNeighbors; i++)
			if (!ok[graph.nodes[currentNode].neighbors[i].name])
				dfs_pointers(graph, graph.nodes[currentNode].neighbors[i].name, ok);
	}
}

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

int main()
{
	graphVertex graphV = readGraphVertex("dfs.in");
	int visited[100] = { 0 };
	int af = 0;
	for (int i = 1; i <= graphV.numNodes; i++)
		visited[i] = 0;
	for (int i = 1; i <= graphV.numNodes; i++)
		if (!visited[i]) {
			af++;
			dfs_pointers(graphV, i, visited);
		}
	FILE* g = fopen("dfs.out", "w");
	fprintf(g, "%d", af);
	fclose(g);
	return 0;
}