Pagini recente » Cod sursa (job #1875940) | Cod sursa (job #2637664) | Cod sursa (job #1571488) | Cod sursa (job #2324019) | Cod sursa (job #2741271)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct vertex {
int name;
struct vertex* next;
} vertex;
typedef struct graphVertex {
int numNodes;
int numEdges;
vertex** nodes;
} graphVertex;
void legare_noduri_lista(vertex** listStart, int value)
{
vertex* nou;
nou = malloc(sizeof(vertex*));
nou->name = value;
nou->next = *listStart;
*listStart = nou;
}
void dfs_vertex(graphVertex graph, int currentNode, int* visited)
{
vertex* listStart;
visited[currentNode] = 1;
for (listStart = graph.nodes[currentNode]; listStart != NULL; listStart = listStart->next)
if (!visited[listStart->name]) {
dfs_vertex(graph, listStart->name, visited);
}
}
graphVertex initializare(const char* fileName)
{
graphVertex graph;
graph.numEdges = 0;
graph.numNodes = 0;
int node1, node2;
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.numEdges; i++) {
fscanf(f, "%d %d", &node1, &node2);
legare_noduri_lista(&graph.nodes[node1], node2);
legare_noduri_lista(&graph.nodes[node2], node1);
}
fclose(f);
return graph;
}
int main()
{
FILE* fout;
graphVertex graf = initializare("dfs.in");
int* vizitat;
int contor = 0;
vizitat = calloc(0, sizeof(int) * graf.numNodes);
for (int i = 0; i < graf.numNodes; i++) {
if (!vizitat[i]) {
dfs_vertex(graf, i, vizitat);
contor++;
}
}
fout = fopen("dfs.out", "w");
fprintf(fout, "%d", contor);
fclose(fout);
return 0;
}