Pagini recente » Cod sursa (job #1579019) | Cod sursa (job #1867185) | Cod sursa (job #2358080) | Cod sursa (job #958089) | Cod sursa (job #2741533)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//POINTERS/VERTEX
typedef struct vertex {
int name;
struct vertex** neighbors;
int numNeighbors;
} vertex;
typedef struct graphVertex {
int numNodes;
int numEdges;
vertex* nodes;
} graphVertex;
int stack[100000];
int indexStack = 0;
void push(int value)
{
if (indexStack < 100000)
stack[indexStack++] = value;
else
printf("Dimensiune stiva depasita!\n");
}
int pop()
{
//verificare daca sunt elemente in stiva
if (indexStack > 0) {
int value = stack[--indexStack];
stack[indexStack] = 0;
return value;
}
printf("Stiva este goala!\n");
return (int)0;
}
void dfs(graphVertex graph, int here)
{
push(here);
int x;
while (indexStack > 0) {
x = pop();
if (graph.nodes[x].name != -1) {
graph.nodes[x].name = -1;
}
for (int k = 0; k < graph.nodes[here].numNeighbors; k++) {
if (graph.nodes[here].neighbors[k]->name != -1) {
push(graph.nodes[here].neighbors[k]->name);
}
}
}
}
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\n", &(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;
}
int a, b;
for (int i = 0; i < graph.numEdges; i++) {
fscanf(f, "%i %i", &a, &b);
a--;
b--;
if (graph.nodes[a].numNeighbors == 0) {
graph.nodes[a].neighbors = (vertex**)malloc(sizeof(vertex*));
}
graph.nodes[a].neighbors = (vertex**)realloc(graph.nodes[a].neighbors, sizeof(vertex**) * (++graph.nodes[a].numNeighbors));
graph.nodes[a].neighbors[graph.nodes[a].numNeighbors - 1] = &(graph.nodes[b]);
if (graph.nodes[b].numNeighbors == 0) {
graph.nodes[b].neighbors = (vertex**)malloc(sizeof(vertex*));
}
graph.nodes[b].neighbors = (vertex**)realloc(graph.nodes[b].neighbors, sizeof(vertex**) * (++graph.nodes[b].numNeighbors));
graph.nodes[b].neighbors[graph.nodes[b].numNeighbors - 1] = &(graph.nodes[a]);
//&(graph.nodes[b]);
}
fclose(f);
return graph;
}
int main()
{
graphVertex graphV = readGraphVertex("dfs.in");
int ct = 0;
for (int i = 0; i < graphV.numNodes; i++) {
if (graphV.nodes[i].name != -1) {
dfs(graphV, i);
ct++;
}
}
FILE* o = fopen("dfs.out", "w");
fprintf(o, "%d", ct);
fclose(o);
return 0;
}