Cod sursa(job #3130059)

Utilizator johnnyyTatar Ioan Dan johnnyy Data 16 mai 2023 18:48:15
Problema Parcurgere DFS - componente conexe Scor 0
Compilator c-64 Status done
Runda Arhiva educationala Marime 2.26 kb
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.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;

graphVertex readGraph(const char *fileName)
{
    graphVertex graph;

    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 = (vertex *)malloc(graph.numNodes * sizeof(vertex));
    }

    for (int i = 0; i < graph.numEdges; i++)
    {
        int left;
        int right;
        fscanf(f, "%i %i", &left, &right);

        graph.nodes[left].neighbors[graph.nodes[left].numNeighbors] = graph.nodes[right];
        graph.nodes[left].numNeighbors++;
    }

    fclose(f);
    return graph;
}

int conex_counter(graphVertex graph, int startNode, bool *visited)
{
    static int counter = 1;
    visited[startNode] = true;

    for (int i = 0; i < graph.nodes[startNode].numNeighbors; i++)
    {
        if (visited[graph.nodes[startNode].neighbors[i].name] == false)
        {
            conex_counter(graph, graph.nodes[startNode].neighbors[i].name, visited);
        }
    }

    if (startNode == 1)
    {
        for (int j = 0; j < graph.numNodes; j++)
        {
            if (visited[j] == false)
            {
                counter++;
                visited[j] = true;

                for (int i = 0; i < graph.nodes[j].numNeighbors; i++)
                {
                    conex_counter(graph, graph.nodes[j].neighbors[i].name, visited);
                }
            }
        }
    }

    return counter;
}

int main()
{
    graphVertex VGraph = readGraph("dfs.in");

    FILE *f = fopen("dfs.out", "w");
    if (f == NULL)
    {
        printf("Nu s-a putut deschide fisierul!");
        exit(1);
    }

    bool visited[100];
    fprintf(f, "%d", conex_counter(VGraph, 1, visited));

    fclose(f);
    return 0;
}