Cod sursa(job #3130071)

Utilizator johnnyyTatar Ioan Dan johnnyy Data 16 mai 2023 19:21:25
Problema Parcurgere DFS - componente conexe Scor 0
Compilator c-64 Status done
Runda Arhiva educationala Marime 2.12 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++;
        graph.nodes[right].neighbors[graph.nodes[right].numNeighbors] = graph.nodes[left];
        graph.nodes[right].numNeighbors++;
    }

    fclose(f);
    return graph;
}

void dfs(graphVertex graph, int startNode, bool *visited)
{
    visited[startNode] = true;

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

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);
    }

    int counter = 1;
    bool visited[100];
    dfs(VGraph, 1, visited);

    for (int i = 0; i < VGraph.numNodes; i++)
    {
        if (visited[i] == false)
        {
            counter++;
            dfs(VGraph, i, visited);
        }
    }

    fprintf(f, "%d", counter);

    fclose(f);
    free(VGraph.nodes);
    return 0;
}