Pagini recente » Cod sursa (job #2455907) | Cod sursa (job #3040590) | Cod sursa (job #1355122) | Cod sursa (job #1443186) | Cod sursa (job #2219391)
#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;
}
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 freemem(struct list *list) {
struct list *aux;
list = list->next;
while (list != NULL) {
aux = list;
list = list->next;
free(aux);
}
}
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);
for (i = 1; i <= n; i++) {
freemem(&list[i]);
}
return 0;
}