Pagini recente » Cod sursa (job #3189838) | Cod sursa (job #3286704) | Cod sursa (job #3266674) | Cod sursa (job #2637336) | Cod sursa (job #2741287)
#include <stdio.h>
#include <stdlib.h>
typedef struct vertex_node {
int value;
struct vertex_node *next;
} vertex_node;
typedef struct graphVertex {
int numNodes;
int numEdges;
vertex_node **nodes;
} graphVertex;
void legare_noduri_lista(vertex_node **listStart, int value)
{
vertex_node *nou;
nou = malloc(sizeof(vertex_node *));
nou->value = value;
nou->next = *listStart;
*listStart = nou;
}
graphVertex read_graphVertex()
{
graphVertex graf;
int dim1, dim2;
int nod1, nod2;
FILE *fin;
fin = fopen("dfs.in", "r");
fscanf(fin, "%d %d", &dim1, &dim2);
graf.numNodes = dim1;
graf.numEdges = dim2;
graf.nodes = malloc(sizeof(vertex_node *) * dim1);
for (int i = 0; i < graf.numEdges; i++) {
fscanf(fin, "%d %d", &nod1, &nod2);
legare_noduri_lista(&graf.nodes[nod1], nod2);
legare_noduri_lista(&graf.nodes[nod2], nod1);
}
fclose(fin);
return graf;
}
void marcheaza_DFS(graphVertex graf, int nod_curent, int *vizitat)
{
vertex_node *listStart;
vizitat[nod_curent] = 1;
for (listStart = graf.nodes[nod_curent]; listStart != NULL; listStart = listStart->next)
if (!vizitat[listStart->value])
marcheaza_DFS(graf, listStart->value, vizitat);
}
void numara_conexe(graphVertex graf, int *vizitat, int *contor)
{
for (int i = 0; i < graf.numNodes; i++)
if (!vizitat[i]) {
(*contor)++;
marcheaza_DFS(graf, i, vizitat);
}
}
int main()
{
graphVertex graf;
FILE *fout;
int *vizitat;
graf = read_graphVertex();
vizitat = calloc(0, sizeof(int) * graf.numNodes);
int contor = 0;
numara_conexe(graf, vizitat, &contor);
fout = fopen("dfs.out", "w");
fprintf(fout, "%d", contor);
fclose(fout);
return 0;
}