Pagini recente » Cod sursa (job #1427294) | Cod sursa (job #3030917) | Monitorul de evaluare | Cod sursa (job #610407) | Cod sursa (job #2741486)
#include <stdio.h>
#include <stdlib.h>
#define size 100005
int visited[size] = {0};
typedef struct vertex {
int name;
int numNeighbours;
struct vertex** neighbours;
} vertex;
typedef struct GraphVertex {
int numNodes;
int numEdges;
vertex* nodes;
} GraphVertex;
GraphVertex ReadFile()
{
FILE* f = fopen("dfs.in", "r");
GraphVertex graph;
fscanf(f, "%d %d", &graph.numNodes, &graph.numEdges);
graph.nodes = (vertex*)malloc(graph.numNodes * sizeof(vertex));
for (int i = 0; i < graph.numNodes; i++) {
graph.nodes[i].numNeighbours = 0;
graph.nodes[i].neighbours = NULL;
graph.nodes[i].name = i + 1;
}
int stanga, dreapta;
int aux = graph.numEdges;
while (aux) {
fscanf(f, "%d %d", &stanga, &dreapta);
graph.nodes[stanga - 1].neighbours = (vertex**)realloc(graph.nodes[stanga - 1].neighbours, (graph.nodes[stanga - 1].numNeighbours + 1) * sizeof(vertex*));
graph.nodes[stanga - 1].neighbours[graph.nodes[stanga - 1].numNeighbours] = graph.nodes + (dreapta - 1);
graph.nodes[dreapta - 1].neighbours = (vertex**)realloc(graph.nodes[dreapta - 1].neighbours, (graph.nodes[dreapta - 1].numNeighbours + 1) * sizeof(vertex*));
graph.nodes[dreapta - 1].neighbours[graph.nodes[dreapta - 1].numNeighbours] = graph.nodes + (stanga - 1);
graph.nodes[stanga - 1].numNeighbours++;
graph.nodes[dreapta - 1].numNeighbours++;
aux--;
}
fclose(f);
return graph;
}
void DFS(GraphVertex graph, int currentnode)
{
visited[currentnode] = 1;
for (int i = 0; i < graph.nodes[currentnode].numNeighbours; i++) {
if (!visited[graph.nodes[currentnode].neighbours[i]->name - 1])
DFS(graph, graph.nodes[currentnode].neighbours[i]->name - 1);
}
}
int main()
{
GraphVertex graph = ReadFile();
int componente = 0;
for (int i = 0; i < graph.numNodes; i++) {
if (!visited[i]) {
DFS(graph, i);
componente++;
}
}
FILE* out = fopen("dfs.out", "w");
fprintf(out, "%d", componente);
fclose(out);
return 0;
}