Pagini recente » Cod sursa (job #1566711) | Cod sursa (job #3267154) | Cod sursa (job #1801501) | Cod sursa (job #2457552) | Cod sursa (job #2741167)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int contor = 0;
typedef struct vertex {
int name;
struct vertex** neighbors;
int numNeighbors;
} vertex;
typedef struct graphVertex {
int numNodes;
int numEdges;
vertex* nodes;
} graphVertex;
graphVertex readGraphVertex(const char* fileName)
{
graphVertex graph;
graph.numEdges = 0;
graph.numNodes = 0;
int node1, node2;
int dim_initial = 10;
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 = malloc(sizeof(vertex*) * dim_initial);
}
for (int i = 0; i < graph.numEdges; i++) {
fscanf(f, "%d %d", &node1, &node2);
graph.nodes[node1].numNeighbors++;
if (graph.nodes[node1].numNeighbors > dim_initial) {
dim_initial += 100;
graph.nodes[node1].neighbors = realloc(graph.nodes[node1].neighbors, sizeof(vertex*) * dim_initial);
}
graph.nodes[node1].neighbors[graph.nodes[node1].numNeighbors - 1] = &graph.nodes[node2];
}
fclose(f);
return graph;
}
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);
}
}
}
int main(int argc, char** argv)
{
graphVertex graphV = readGraphVertex("dfs.in");
int visited4[100005] = {0}; //we assume fewer than 100 nodes
for (int i = 0; i < graphV.numNodes; i++) {
if (visited4[i] == 0)
contor++;
dfs_vertex(graphV, i, visited4);
}
FILE* fout;
fout = fopen("dfs.out", "w");
if (fout == NULL) {
printf("Eroare la deschiderea fisierului");
return 0;
}
fprintf(fout, "%d", contor);
fclose(fout);
printf("\n");
}