Cod sursa(job #2741500)

Utilizator stefan.lascuzeanuLascuzeanu Stefan-Andrei stefan.lascuzeanu Data 16 aprilie 2021 11:22:03
Problema BFS - Parcurgere in latime Scor 30
Compilator c-64 Status done
Runda Arhiva educationala Marime 2.71 kb
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//POINTERS/VERTEX
typedef struct vertex {
	int name;
	struct vertex** neighbors;
	int numNeighbors;
	//	int* weights;
} vertex;

typedef struct graphVertex {
	int numNodes;
	int numEdges;
	vertex* nodes;
} graphVertex;

int stack[100];
int indexStack = 0;

void push(int value)
{
	if (indexStack < 100)
		stack[indexStack++] = value;
	else
		printf("Dimensiune stiva depasita!\n");
}

int pop()
{
	//verificare daca sunt elemente in stiva
	if (indexStack > 0) {
		int value = stack[--indexStack];
		stack[indexStack] = 0;
		return value;
	}
	printf("Stiva este goala!\n");
	return (int)0;
}

void bfs(graphVertex graph, int startNode)
{
	int queue[100], i = 0, j = 0, ct;
	queue[j] = startNode;
	int visited[100001] = {0}, cost[100001] = {0};
	while (i <= j) {
		visited[queue[i]] = 1;
		for (int k = 0; k < graph.nodes[queue[i] - 1].numNeighbors; k++) {
			if (visited[graph.nodes[queue[i] - 1].neighbors[k]->name] == 0) {
				ct = 0;
				for (int l = i + 1; l <= j; l++) {
					if (queue[l] == graph.nodes[queue[i] - 1].neighbors[k]->name) ct = 1;
				}

				if (ct == 0) {
					queue[++j] = graph.nodes[queue[i] - 1].neighbors[k]->name;
					cost[queue[j]] = cost[queue[i]] + 1;
				}
			}
		}
		i++;
	}
	for (i = 1; i <= graph.numNodes; i++) {
		if (visited[i] == 0) cost[i] = -1;
	}
	FILE* o = fopen("bfs.out", "w");
	if (o == NULL) return;
	for (i = 1; i <= graph.numNodes; i++) {
		fprintf(o, "%d ", cost[i]);
	}
	printf("%d ", queue[i]);  //
}

graphVertex readGraphVertex(const char* fileName, int* start)
{
	graphVertex graph;
	graph.numEdges = 0;
	graph.numNodes = 0;
	FILE* f = fopen(fileName, "r");
	if (f == NULL)
		return graph;

	fscanf(f, "%i %i %i\n", &(graph.numNodes), &(graph.numEdges), start);
	graph.nodes = (vertex*)malloc(sizeof(vertex) * graph.numNodes);
	if (graph.nodes == NULL)
		return graph;
	for (int i = 0; i < graph.numNodes; i++) {
		graph.nodes[i].name = i + 1;
		graph.nodes[i].numNeighbors = 0;
		graph.nodes[i].neighbors = NULL;
	}
	int a, b;
	for (int i = 0; i < graph.numEdges; i++) {
		fscanf(f, "%i %i", &a, &b);
		if (graph.nodes[a - 1].numNeighbors == 0) {
			graph.nodes[a - 1].neighbors = (vertex**)malloc(sizeof(vertex*));
		}
		graph.nodes[a - 1].neighbors = (vertex**)realloc(graph.nodes[a - 1].neighbors, sizeof(vertex**) * (++graph.nodes[a - 1].numNeighbors));
		graph.nodes[a - 1].neighbors[graph.nodes[a - 1].numNeighbors - 1] = &(graph.nodes[b - 1]);
		//&(graph.nodes[b]);
	}
	fclose(f);
	return graph;
}

int main()
{
	//POINTERS/VERTEX
	int start;
	graphVertex graphV = readGraphVertex("bfs.in", &start);

	bfs(graphV, start);
	return 0;
}