Pagini recente » Cod sursa (job #3178725) | Cod sursa (job #3281882) | Cod sursa (job #3132337) | Cod sursa (job #1367843) | Cod sursa (job #2741260)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct vertex {
int name;
struct vertex** neighbors;
int numNeighbors;
} vertex;
typedef struct graphVertex {
int numNodes;
int numEdges;
vertex* nodes;
} graphVertex;
void dfs_vertex(graphVertex graph, int currentNode, int* visited)
{
visited[currentNode] = 1;
for (int j = 0; j < graph.nodes[currentNode].numNeighbors; j++) {
if ((!visited[graph.nodes[currentNode].neighbors[j]->name])) {
dfs_vertex(graph, graph.nodes[currentNode].neighbors[j]->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.numNodes; i++) {
graph.nodes[i].name = i;
graph.nodes[i].numNeighbors = 0;
graph.nodes[i].neighbors = NULL;
}
for (int i = 0; i < graph.numEdges; i++) {
fscanf(f, "%d %d", &node1, &node2);
if (graph.nodes[node1].numNeighbors == 0) {
graph.nodes[node1].neighbors = malloc(sizeof(vertex*) * graph.numNodes);
}
graph.nodes[node1].neighbors[graph.nodes[node1].numNeighbors] = &graph.nodes[node2];
graph.nodes[node1].numNeighbors++;
}
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[graf.nodes[i].name]) {
dfs_vertex(graf, i, vizitat);
contor++;
}
}
fout = fopen("dfs.out", "w");
fprintf(fout, "%d", contor);
fclose(fout);
return 0;
}