Cod sursa(job #2902752)

Utilizator PukichoBan Alex Pukicho Data 16 mai 2022 19:29:36
Problema Parcurgere DFS - componente conexe Scor 55
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.3 kb
#define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#include <stdio.h>

typedef struct nod {
	int id;
	int numNeihgbors;
	int *neighbors;
}nod;

int numComponents;
int* nodComponents;

void dfs(nod* graph, int n, int source)
{
	nodComponents[source] = numComponents;
	for (int i = 0; i < graph[source].numNeihgbors; i++)
		if (nodComponents[graph[source].neighbors[i] - 1] == 0)
			dfs(graph, n, graph[source].neighbors[i] - 1);
}

int main()
{
	int n, m;
	FILE* f = fopen("dfs.in", "r");
	fscanf(f, "%d%d", &n, &m);
	nodComponents = (int*)malloc(n * sizeof(int));
	for (int k = 0; k < n; k++)
		nodComponents[k] = 0;

	nod* graph = (nod*)malloc(n * sizeof(nod));
	int i;
	for (i = 0; i < n; i++)
	{
		graph[i].id = i + 1;
		graph[i].numNeihgbors = 0;
		graph[i].neighbors = (int*)malloc((n - 1) * sizeof(int));
	}
	int x, y;
	for (i = 0; i < m; i++)
	{
		fscanf(f, "%d%d", &x, &y);
		graph[x - 1].neighbors[graph[x - 1].numNeihgbors] = y;
		graph[x - 1].numNeihgbors++;
		graph[y - 1].neighbors[graph[y - 1].numNeihgbors] = x;
		graph[y - 1].numNeihgbors++;
	}

	fclose(f);

	for (i = 0; i < n; i++)
		if (nodComponents[i] == 0)
		{ 
			numComponents++;
			dfs(graph, n, i);
		}

	FILE* g = fopen("dfs.out", "w");
	fprintf(g, "%d", numComponents);
	fclose(g);

	return 0;
}