Cod sursa(job #2741077)

Utilizator luca_raduluca 123 luca_radu Data 15 aprilie 2021 14:44:18
Problema Parcurgere DFS - componente conexe Scor 30
Compilator c-64 Status done
Runda Arhiva educationala Marime 2.74 kb
#include <stdbool.h>
#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);
	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);
		left--;
		right--;
		if (graph.nodes[left].numNeighbors == 0) {
			graph.nodes[left].numNeighbors++;
			graph.nodes[left].neighbors = (vertex**)malloc(graph.nodes[left].numNeighbors * sizeof(vertex*));
			graph.nodes[left].neighbors[graph.nodes[left].numNeighbors - 1] = &graph.nodes[right];
		} else {
			graph.nodes[left].numNeighbors++;
			graph.nodes[left].neighbors = (vertex**)realloc(graph.nodes[left].neighbors, graph.nodes[left].numNeighbors * sizeof(vertex*));
			graph.nodes[left].neighbors[graph.nodes[left].numNeighbors - 1] = &graph.nodes[right];
		}
		if (graph.nodes[right].numNeighbors == 0) {
			graph.nodes[right].numNeighbors++;
			graph.nodes[right].neighbors = (vertex**)malloc(graph.nodes[right].numNeighbors * sizeof(vertex*));
			graph.nodes[right].neighbors[graph.nodes[right].numNeighbors - 1] = &graph.nodes[left];
		} else {
			graph.nodes[right].numNeighbors++;
			graph.nodes[right].neighbors = (vertex**)realloc(graph.nodes[right].neighbors, graph.nodes[left].numNeighbors * sizeof(vertex*));
			graph.nodes[right].neighbors[graph.nodes[right].numNeighbors - 1] = &graph.nodes[left];
		}
	}
	fclose(f);
	return graph;
}
void dfs_pointers(graphVertex graph, int currentNode, char* visited)
{
	if (visited[currentNode] == 1)
		return;
	visited[currentNode] = 1;
	for (int i = 0; i < graph.nodes[currentNode].numNeighbors; i++) {
		if (!visited[graph.nodes[currentNode].neighbors[i]->name]) {
			dfs_pointers(graph, graph.nodes[currentNode].neighbors[i]->name, visited);
		}
	}
}
int main(int argc, char* argv[])
{
	graphVertex graphV = readGraphVertex("dfs.in");
	char* visited = (char*)malloc(100005);
	int count = 0;
	int j;
	for (int i = 0; i < graphV.numNodes; i++) {
		if (!visited[i]) {
			count++;
			dfs_pointers(graphV, i, visited);
		}
	}
	FILE* g = fopen("dfs.out", "w");
	fprintf(g, "%d", count);
	return 0;
}