Mai intai trebuie sa te autentifici.
Cod sursa(job #2219383)
Utilizator | Data | 8 iulie 2018 17:14:23 | |
---|---|---|---|
Problema | Parcurgere DFS - componente conexe | Scor | 0 |
Compilator | c | Status | done |
Runda | Arhiva educationala | Marime | 1.68 kb |
#include <stdio.h>
#include <stdlib.h>
struct list {
int node;
struct list *next;
} list[100000];
char visited[100000];
void add_neighbour(int vertex, int neighbour) {
struct list *aux;
aux = malloc(sizeof(struct list));
aux->node = neighbour;
aux->next = list[vertex].next;
list[vertex].next = aux;
}
int search_neighbour(struct list vertex) {
struct list aux = vertex;
while (aux.next != NULL) {
printf("%d ", aux.next->node);
aux = *aux.next;
}
}
void dfs(int vertex) {
struct list aux = list[vertex];
visited[vertex] = 1;
if (!visited[aux.node]) {
dfs(aux.node);
visited[aux.node] = 1;
}
while (aux.next != NULL) {
if (!visited[aux.next->node]) {
dfs(aux.next->node);
visited[aux.next->node] = 1;
}
aux = *aux.next;
}
}
void free_alloc(int n) {
int i;
for (i = 1; i <= n; i++) {
while (list[i].next != NULL) {
free(&list[i]);
list[i] = *list[i].next;
}
free(&list[i]);
}
}
int main()
{
int conexe = 0;
int n, m;
int k, j;
int i;
FILE *in;
FILE *out;
in = fopen("dfs.in", "r");
fscanf(in, "%d %d", &n, &m);
for (i = 0; i < m; i++) {
fscanf(in, "%d %d", &k, &j);
add_neighbour(k, j);
add_neighbour(j, k);
}
fclose(in);
for (i = 1; i <= n; i++) {
if (!visited[i]) {
dfs(i);
conexe++;
}
}
out = fopen("dfs.out", "w");
fprintf(out, "%d", conexe);
fclose(out);
free_alloc(n);
return 0;
}