Cod sursa(job #2888694)

Utilizator anamaria140402Balacescu Anamaria anamaria140402 Data 11 aprilie 2022 19:15:22
Problema Parcurgere DFS - componente conexe Scor 0
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.98 kb
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//EDGES
typedef struct edge {
	int leftNode;
	int rightNode;
} edge;

typedef struct graphEdges {
	edge* edges;
	int numNodes;
	int numEdges;
} graphEdges;

void dfs_edges(graphEdges graph, int currentNode, int* visited)
{
	visited[currentNode] = 1;
	//printf("%d ", currentNode);
	//printf("%d ", currentNode);
	for(int i = 0; i < graph.numEdges; i++)
	{
		if(graph.edges[i].leftNode == currentNode)
		{
			if(!visited[graph.edges[i].rightNode])
			{
				dfs_edges(graph, graph.edges[i].rightNode, visited);
			}
		}
	}
}

graphEdges readGraphEdgeList(const char* fileName)
{
	graphEdges graph;
	graph.numEdges = 0;
	graph.edges = NULL;
	FILE* f = fopen(fileName, "r");
	if (f == NULL)
		return graph;

	//TODO

	int n = 0;
	fscanf(f, "%d", &n);
	graph.numNodes = n;
	
	int m = 0;
	fscanf(f, "%d", &m);
	graph.numEdges = m;

	graph.edges = (edge*) malloc (m * sizeof(edge));
	//int no = 0;
	for(int i = 0 ; i < graph.numEdges; i++)
	{
		int auxi = 0;
		int auxj = 0;
		fscanf(f, "%d", &auxi);
		fscanf(f, "%d", &auxj);
		//graph.edges = (edge*)realloc(graph.edges, (m + 1) * sizeof(edge));
		graph.edges[i].leftNode = auxi;
		graph.edges[i].rightNode = auxj;
		//m++;
	}
	//graph.numEdges = m;

	fclose(f);
	return graph;
}


int main()
{
	//EDGES
	graphEdges graphE = readGraphEdgeList("dfs.in");
	int visited2[100] = {0};  //we assume fewer than 100 nodes
	int poz = 0;
    int ok = 0;
    int nrconex = 0;
    do{
        ok = 0;
        for(int i = 0; i < graphE.numNodes && ok == 0; i++)
            if(visited2[i] == 0)
            {
                ok = 1;
                poz = i;
            }
        if(ok == 1)
        {
            nrconex++;
            dfs_edges(graphE, poz, visited2);
	        //for(int i = 0; i < graphE.numNodes; i++)
                //printf("%d %d\n", i, visited2[i]);
        }
    }while(ok == 1);
    FILE* g = fopen("dfs.out", "w");
    fprintf(g, "%d", nrconex);
    fclose(g);
    //printf("%d", nrconex);
	return 0;
}