Pagini recente » Cod sursa (job #1223501) | Cod sursa (job #3131252) | Cod sursa (job #1492961) | Cod sursa (job #1589469) | Cod sursa (job #2740500)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct graphVertex {
int numNeighbours;
int* neighbours;
int name;
int weights;
} graphVertex;
int NumberOfNodes, NumberOfEdges;
graphVertex* readGraphVertex(const char* fileName)
{
FILE* f = fopen(fileName, "r");
if (f == NULL)
return NULL;
fscanf(f, "%i%i", &NumberOfNodes, &NumberOfEdges);
graphVertex* nodes = (graphVertex*)malloc((NumberOfNodes + 1) * sizeof(graphVertex));
if (nodes == NULL)
return nodes;
for (int i = 1; i <= NumberOfNodes; i++) {
nodes[i].name = i;
nodes[i].numNeighbours = 0;
nodes[i].neighbours = NULL;
nodes[i].weights = -1;
}
int stanga, dreapta;
for (int i = 0; i < NumberOfEdges; i++) {
fscanf(f, "\n%i%i", &stanga, &dreapta);
nodes[stanga].numNeighbours++;
nodes[stanga].neighbours = (int*)realloc(nodes[stanga].neighbours, (nodes[stanga].numNeighbours + 1) * sizeof(int));
nodes[stanga].neighbours[nodes[stanga].numNeighbours - 1] = dreapta;
}
fclose(f);
return nodes;
}
void dfs(graphVertex* graph, int root)
{
for (int i = 0; i < graph[root].numNeighbours; i++)
if (graph[graph[root].neighbours[i]].weights == -1) {
graph[graph[root].neighbours[i]].weights = graph[root].weights;
dfs(graph, graph[root].neighbours[i]);
}
}
int main()
{
graphVertex* graph = readGraphVertex("dfs.in");
int nrconexe = 1;
for (int j = 1; j <= NumberOfNodes; j++) {
if (graph[j].weights == -1) {
graph[j].weights = nrconexe;
dfs(graph, j);
nrconexe++;
}
}
FILE* f = fopen("dfs.out", "w");
fprintf(f, "%d", nrconexe - 1);
fclose(f);
}