Cod sursa(job #2740134)

Utilizator teogeoBanu Teodora teogeo Data 11 aprilie 2021 15:41:50
Problema Parcurgere DFS - componente conexe Scor 5
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.44 kb
#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;
}