Pagini recente » Cod sursa (job #1454364) | Cod sursa (job #1097696) | Cod sursa (job #2584900) | Cod sursa (job #1389899) | Cod sursa (job #2740461)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct vertex {
int name;
struct vertex** neighbors;
int numNeighbors;
// int* weights;
} vertex;
typedef struct graphVertex {
int numNodes;
int numEdges;
int root;
vertex* nodes;
} graphVertex;
graphVertex readGraphVertex(const char* fileName)
{
graphVertex graph;
graph.numEdges = 0;
graph.numNodes = 0;
FILE* f = fopen(fileName, "r");
if (f == NULL)
return graph;
fscanf(f, "%i%i%i", &(graph.numNodes), &(graph.numEdges), &(graph.root));
graph.nodes = (vertex*)malloc(sizeof(vertex) * (graph.numNodes + 1));
if (graph.nodes == NULL)
return graph;
for (int i = 1; i <= graph.numNodes; i++) {
graph.nodes[i].name = i;
graph.nodes[i].numNeighbors = 0;
graph.nodes[i].neighbors = NULL;
}
int stanga, dreapta;
for (int i = 0; i < graph.numEdges; i++) {
fscanf(f, "\n%i%i", &stanga, &dreapta);
if (graph.nodes[stanga].numNeighbors == 0)
graph.nodes[stanga].neighbors = (vertex**)malloc(sizeof(vertex*));
else
graph.nodes[stanga].neighbors = (vertex**)realloc(graph.nodes[stanga].neighbors, (graph.nodes[stanga].numNeighbors + 1) * sizeof(vertex*));
graph.nodes[stanga].neighbors[graph.nodes[stanga].numNeighbors] = (vertex*)malloc(sizeof(vertex));
graph.nodes[stanga].neighbors[graph.nodes[stanga].numNeighbors] = &graph.nodes[dreapta];
graph.nodes[stanga].numNeighbors++;
}
fclose(f);
return graph;
}
int queue[100];
int indexQueue = 0;
void pushqueue(int value)
{
if (indexQueue < 100)
queue[indexQueue++] = value;
else
printf("Dimensiune coada depasita!\n");
}
int popqueue()
{
if (indexQueue > 0) {
int value = queue[0];
for (int i = 1; i < indexQueue; i++)
queue[i - 1] = queue[i];
indexQueue--;
return value;
}
printf("Coada este goala!\n");
return (int)0;
}
void bfs(graphVertex graph, int startnode, int* visited)
{
visited[startnode] = 0;
pushqueue(startnode);
while (indexQueue) {
int value = popqueue();
for (int i = 0; i < graph.nodes[value].numNeighbors; i++)
if (visited[graph.nodes[value].neighbors[i]->name] == -1) {
visited[graph.nodes[value].neighbors[i]->name] = 1 + visited[graph.nodes[value].name];
pushqueue(graph.nodes[value].neighbors[i]->name);
}
}
}
int main()
{
int visited[100001];
graphVertex graph = readGraphVertex("bfs.in");
for (int i = 1; i <= graph.numNodes; i++)
visited[i] = -1;
bfs(graph, graph.root, visited);
FILE* f = fopen("bfs.out", "w");
for (int i = 1; i <= graph.numNodes; i++)
fprintf(f, "%i ", visited[i]);
fclose(f);
}