Cod sursa(job #1706937)

Utilizator popcristianvladVlad Pop popcristianvlad Data 23 mai 2016 21:06:45
Problema Parcurgere DFS - componente conexe Scor 35
Compilator c Status done
Runda Arhiva educationala Marime 2.3 kb
#include <stdio.h>
#include <stdlib.h>

struct nod{
    int key;
    int marked;
};

struct nod_adj{
    struct nod *node;
    struct nod_adj *next;
};


int size;

void APPEND_NODE1(struct nod_adj **adj, struct nod *starting_node, struct nod *ending_node){
    struct nod_adj *n = *(adj + starting_node->key);
    while(n->next != NULL)
        n = n->next;
    struct nod_adj *new_node = (struct nod_adj *)malloc(sizeof(struct nod_adj));
    new_node->node = ending_node;
    new_node->next = NULL;
    n->next = new_node;
}

void APPEND_NODE2(struct nod_adj **adj, struct nod *starting_node, struct nod *ending_node){
    struct nod_adj *n = *(adj + starting_node->key);
    while(n->next != NULL)
        n = n->next;
    struct nod_adj *new_node = (struct nod_adj *)malloc(sizeof(struct nod_adj));
    new_node->node = ending_node;
    new_node->next = NULL;
    n->next = new_node;
}

void DFS(struct nod_adj **adj, struct nod *node){
    (*(adj + node->key))->node->marked = 1;
    struct nod_adj *n = *(adj + node->key);
    n = n->next;
    while(n != NULL){
        if(n->node->marked == 0)
            DFS(adj, n->node);
        n = n->next;
    }
}


int main(){
    FILE *f = fopen("dfs.in", "r");
    FILE *g = fopen("dfs.out", "w");
    int nr_varfuri, nr_muchii, i, componente_conexe = 0;
    fscanf(f, "%d %d", &nr_varfuri, &nr_muchii);
    struct nod_adj **adj = (struct nod_adj **)malloc(nr_varfuri*sizeof(struct nod_adj));
    for(i=0; i<nr_varfuri; i++){
        *(adj + i) = (struct nod_adj *)malloc(sizeof(struct nod_adj));
        struct nod *node = (struct nod *)malloc(sizeof(struct nod));
        node->key = i;
        node->marked = 0;
        (*(adj + i))->node = node;
        (*(adj + i))->next = NULL;
    }

    for(i=0; i<nr_muchii; i++){
        int c1, c2;
        fscanf(f, "%d %d", &c1, &c2);
        struct nod *starting_node = (*(adj + c1))->node;
        struct nod *ending_node = (*(adj + c2))->node;
        APPEND_NODE1(adj, starting_node, ending_node);
        APPEND_NODE2(adj, ending_node, starting_node);
    }
    for(i=0 ;i<nr_varfuri; i++)
        if((*(adj + i))->node->marked == 0){
            DFS(adj, (*(adj + i))->node);
            componente_conexe++;
    }
    fprintf(g, "%d", componente_conexe);
    return 0;
}