Pagini recente » Cod sursa (job #551954) | Cod sursa (job #3195988) | Cod sursa (job #2978681) | Cod sursa (job #1885266) | Cod sursa (job #2740134)
#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(int start, nodes* graph)
{
visited[start] = 1;
for (int i = 0; i < graph[start].numNeighbours; i++)
{
if (!visited[graph[start].neighbours[i]])
DFS(graph[start].neighbours[i], graph);
}
}
int main() {
nodes* graph = readFile("dfs.in");
DFS(graph[1].name, 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;
}