Cod sursa(job #2742924)

Utilizator JipiJipianu Mihnea Jipi Data 22 aprilie 2021 12:36:48
Problema Parcurgere DFS - componente conexe Scor 100
Compilator c-64 Status done
Runda Arhiva educationala Marime 2.38 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 stack[100000];
int indexStack = 0;

void push(int value)
{
	if (indexStack < 100000)
		stack[indexStack++] = value;
	else
		printf("Dimensiune stiva depasita!\n");
}

int pop()
{
	if (indexStack > 0) {
		int value = stack[--indexStack];
		stack[indexStack] = 0;
		return value;
	}
	printf("Stiva este goala!\n");
	return (int)0;
}

void dfs(graphVertex graph, int here)
{
	push(here);
	int x;
	while (indexStack > 0) {
		x = pop();
		graph.nodes[x].name = -1;
		for (int k = 0; k < graph.nodes[x].numNeighbors; k++) {
			if (graph.nodes[x].neighbors[k]->name != -1) push(graph.nodes[x].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]);
		if (graph.nodes[b].numNeighbors == 0) {
			graph.nodes[b].neighbors = (vertex**)malloc(sizeof(vertex*));
		}
		graph.nodes[b].neighbors = (vertex**)realloc(graph.nodes[b].neighbors, sizeof(vertex**) * (++graph.nodes[b].numNeighbors));
		graph.nodes[b].neighbors[graph.nodes[b].numNeighbors - 1] = &(graph.nodes[a]);
		//&(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;
}