Pagini recente » Cod sursa (job #1079370) | Cod sursa (job #1491348) | Cod sursa (job #460873) | Cod sursa (job #1924327) | Cod sursa (job #2741915)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct vertex {
int name;
int* neighbors;
int numNeighbors;
// int* weights;
} vertex;
typedef struct graphVertex {
int numNodes;
int numEdges;
vertex* nodes;
} graphVertex;
int visited[100001] = {0};
void dfs(graphVertex graph, int currentNode)
{
visited[currentNode] = 1;
for (int i = 1; i <= graph.nodes[currentNode].numNeighbors; i++) {
if (visited[graph.nodes[currentNode].neighbors[i]] == 0)
dfs(graph, graph.nodes[currentNode].neighbors[i]);
}
}
int N, M;
graphVertex readGraphVertex(const char* fileName)
{
graphVertex graph;
graph.numEdges = 0;
graph.numNodes = 0;
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 + 1));
if (graph.nodes == NULL)
return graph;
for (int i = 1; i <= graph.numNodes; i++) {
graph.nodes[i].name = i;
graph.nodes[i].numNeighbors = 0;
graph.nodes[i].neighbors = NULL;
}
int e1, e2;
for (int i = 1; i <= graph.numEdges; i++) {
fscanf(f, "%d %d", &e1, &e2);
graph.nodes[e1].numNeighbors++;
graph.nodes[e1].neighbors = (int*)realloc(graph.nodes[e1].neighbors, sizeof(int) * (graph.nodes[e1].numNeighbors + 1));
graph.nodes[e1].neighbors[graph.nodes[e1].numNeighbors] = e2;
}
fclose(f);
return graph;
}
int main()
{
int count = 0;
graphVertex graph = readGraphVertex("dfs.in");
for (int i = 1; i <= graph.numNodes; i++) {
if (visited[graph.nodes[i].name] == 0) {
count++;
dfs(graph, graph.nodes[i].name);
}
}
printf("%i", count);
}