Pagini recente » Cod sursa (job #2196690) | Cod sursa (job #1710875) | Cod sursa (job #1985712) | Cod sursa (job #2035111) | Cod sursa (job #2741181)
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
typedef struct vertex {
int name;
struct vertex* neighbors;
int numNeighbors;
} vertex;
typedef struct graphVertex {
int numNodes;
int numEdges;
vertex* nodes;
} graphVertex;
void dfs_pointers(graphVertex graph, int currentNode, int* ok)
{
if (!ok[currentNode]) {
ok[currentNode] = 1;
for (int i = 0; i < graph.nodes[currentNode].numNeighbors; i++)
if (!ok[graph.nodes[currentNode].neighbors[i].name])
dfs_pointers(graph, graph.nodes[currentNode].neighbors[i].name, ok);
}
}
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 = 0; i <= graph.numNodes; i++) {
graph.nodes[i].name = i;
graph.nodes[i].numNeighbors = 0;
graph.nodes[i].neighbors = (vertex*)malloc(10 * sizeof(vertex));;
}
for (int i = 0; i < graph.numEdges; i++) {
int a, b;
fscanf(f, "%d%d", &a, &b);
graph.nodes[a].numNeighbors++;
graph.nodes[a].neighbors[graph.nodes[a].numNeighbors - 1] = graph.nodes[b];
graph.nodes[b].numNeighbors++;
graph.nodes[b].neighbors[graph.nodes[b].numNeighbors - 1] = graph.nodes[a];
}
fclose(f);
return graph;
}
int main()
{
graphVertex graphV = readGraphVertex("dfs.in");
int visited[100] = { 0 };
int af = 0;
for (int i = 1; i <= graphV.numNodes; i++)
visited[i] = 0;
for (int i = 1; i <= graphV.numNodes; i++)
if (!visited[i]) {
af++;
dfs_pointers(graphV, i, visited);
}
FILE* g = fopen("dfs.out", "w");
fprintf(g, "%d", af);
fclose(g);
return 0;
}