Cod sursa(job #2740449)

Utilizator radu01Toader Radu Marian radu01 Data 13 aprilie 2021 00:05:27
Problema BFS - Parcurgere in latime Scor 0
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct graph {
	int name;
	int numNeighbours;
	int* neighbours;
} graph;

int N, M;
int visited[100001];

graph* read(const char* filename)
{
	FILE* f = fopen(filename, "r");
	if (f == NULL) {
		return NULL;
	}
	fscanf(f, "%d %d", &N, &M);
	graph* newGraph = (graph*)malloc(sizeof(graph) * (N + 1));

	for (int i = 1; i <= N; i++) {
		newGraph[i].name = i;
		newGraph[i].numNeighbours = 0;
		newGraph[i].neighbours = NULL;
	}

	int left, right;
	for (int i = 0; i < M; i++) {
		fscanf(f, "%d %d", &left, &right);
		newGraph[left].numNeighbours++;
		newGraph[left].neighbours = (int*)realloc(newGraph[left].neighbours, sizeof(int) * newGraph[left].numNeighbours);
		newGraph[left].neighbours[newGraph[left].numNeighbours - 1] = right;
	}

	fclose(f);
	return newGraph;
}

void DFS(graph* list, int current)
{
	visited[current] = 1;
	for (int i = 0; i < list[current].numNeighbours; i++) {
		if (visited[list[current].neighbours[i]] == 0)
			DFS(list, list[current].neighbours[i]);
	}
}

int main()
{
	graph* graphV = read("dfs.in");
	int count = 0;

	for (int i = 1; i <= N; i++) {
		if (visited[i] != 1) {
			count++;
			DFS(graphV, i);
		}
	}

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

	return 0;
}