Pagini recente » Cod sursa (job #1005236) | Cod sursa (job #2646377) | Cod sursa (job #697441) | Cod sursa (job #441983) | Cod sursa (job #2740122)
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#define MAX 100001
typedef struct nodes {
int name;
int numNeighbours;
int* neighbours;
}nodes;
int N, M;
int visited[MAX];
nodes* readFile(const char* filename) {
FILE* f = fopen(filename, "r");
fscanf(f, "%d %d", &N, &M);
nodes* graph = (nodes*)malloc((N + 1) * sizeof(nodes));
for (int i = 1; i <= N; i++) {
graph[i].name = i;
graph[i].numNeighbours = 0;
graph[i].neighbours = NULL;
}
int x, y;
for (int i = 0; i < M; i++) {
fscanf(f,"%d %d", &x, &y);
graph[x].numNeighbours++;
graph[x].neighbours = (int*)realloc(graph[x].neighbours, graph[x].numNeighbours * sizeof(int));
graph[x].neighbours[graph[x].numNeighbours - 1] = y;
graph[y].numNeighbours++;
graph[y].neighbours = (int*)realloc(graph[y].neighbours, graph[y].numNeighbours * sizeof(int));
graph[y].neighbours[graph[y].numNeighbours - 1] = x;
}
fclose(f);
return graph;
}
void DFS(nodes start, nodes* graph)
{
visited[start.name] = 1;
for (int i = 0; i < start.numNeighbours; i++)
{
if (!visited[start.neighbours[i]])
DFS(graph[start.neighbours[i]], graph);
}
}
int main() {
nodes* graph = readFile("dfs.in");
DFS(graph[1], graph);
int count = 0;
for (int i = 1; i <= N; i++)
if (visited[i] == 0)
count++;
FILE* f = fopen("dfs.out", "w");
fprintf(f,"%d", count);
fclose(f);
return 0;
}