Cod sursa(job #2589986)

Utilizator RaduQQTCucuta Radu RaduQQT Data 27 martie 2020 12:13:23
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.82 kb
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>

#define type int

typedef struct listNode
{
	type element;
	listNode* next;
	listNode* prev;
};

void pushCoada(listNode*& first, listNode*& last, type element)
{
	listNode* node = (listNode*)malloc(sizeof(listNode));
	node->element = element;
	node->next = NULL;
	node->prev = last;
	if (last == NULL)
	{
		last = node;
		first = node;
		return;
	}

	last->next = node;
	last = last->next;
}

listNode* graph[1000001];
void insertNodeInGraph(int graphNo, type element)
{
	listNode* p = graph[graphNo];
	if (p == NULL)
		pushCoada(graph[graphNo], p, element);
	else
	{
		while (p->next != NULL)
			p = p->next;
		pushCoada(graph[graphNo], p, element);
	}
}

int n, m, visited[1000001];
void readGraph(char* filename)
{
	FILE* fin = fopen(filename, "r");

	fscanf(fin, "%d%d", &n, &m);
	int x, y;

	for (int i = 1; i <= n; i++)
	{
		graph[i] = NULL;
	}
	for (int i = 1; i <= m; i++)
	{
		fscanf(fin, "%d%d", &x, &y);
		insertNodeInGraph(x, y);
		insertNodeInGraph(y, x);
	}
}

void PrintGraph()
{
	int ok = 0;
	for (int i = 1; i <= n; i++)
	{
		if (graph[i] != NULL)
		{
			ok++;
			printf("%d ", i);
		}
		while (graph[i] != NULL)
		{
			printf("%d ", graph[i]->element);
			graph[i] = graph[i]->next;
		}
		if (ok)
			printf("\n");
		ok = 0;
	}
}
void BFS_recursiv(int i)
{
	listNode* p;

	//printf("%d ", i);
	p = graph[i];
	visited[i] = 1;
	while (p != NULL)
	{
		i = p->element;

		if (!visited[i])
			BFS_recursiv(i);
		p = p->next;
	}
}
int main()
{
	readGraph((char*)"dfs.in");
	//PrintGraph();
	int conexe = 0;
	for (int i = 1; i <= n; i++)
		if (visited[i] == 0)
		{
			conexe++;
			BFS_recursiv(i);
		}
	FILE* fout = fopen("dfs.out", "w");
	fprintf(fout,"%d", conexe);
}