Pagini recente » Cod sursa (job #128339) | Cod sursa (job #670089) | Cod sursa (job #1686907) | Cod sursa (job #1667244) | Cod sursa (job #2740737)
#define _CRT_SECURE_NO_WARNINGS
#define size 100000
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct vertex
{
int num;
int* canGo;
}vertex;
typedef struct GraphVertex
{
int* cost;
int numNodes;
int numEdges;
vertex* nodes;
}GraphVertex;
int queue[size];
int queueIndex = 0;
int visited[size] = { 0 };
void enqueue(int value)
{
if (queueIndex < size)
queue[queueIndex++] = value;
else
return;
}
int dequeue()
{
if (queueIndex == 0) {
printf("Coada este goala");
return -1;
}
int value = queue[0];
for (int i = 0; i < queueIndex - 1; i++)
queue[i] = queue[i + 1];
queueIndex--;
return value;
}
GraphVertex readFile(const char* fname,int *source)
{
GraphVertex graph;
graph.nodes = NULL;
graph.cost = NULL;
FILE* fptr = fopen(fname, "r");
int numNodes, edges, s;
fscanf(fptr, "%d %d %d", &numNodes, &edges, &s);
*source = s;
graph.nodes = (vertex*)malloc(numNodes * sizeof(vertex));
graph.cost = (int*)malloc(numNodes * sizeof(int));
for (int i = 0; i < numNodes; i++)
{
graph.nodes[i].canGo = NULL;
graph.nodes[i].num = 0;
graph.cost[i] = -1;
}
graph.numEdges = edges;
graph.numNodes = numNodes;
int left,right;
while (edges)
{
fscanf(fptr, "%d %d", &left, &right);
graph.nodes[left-1].canGo = (int*)realloc(graph.nodes[left-1].canGo, (graph.nodes[left-1].num + 1) * sizeof(int));
graph.nodes[left-1].canGo[graph.nodes[left-1].num] = right;
graph.nodes[left-1].num++;
edges--;
}
fclose(fptr);
return graph;
}
void bfs(GraphVertex graph,int source)
{
enqueue(source);
graph.cost[source-1] = 0;
while (queueIndex)
{
int current = dequeue();
visited[current] = 1;
for (int i = 0; i < graph.nodes[current-1].num; i++)
{
if (!visited[graph.nodes[current-1].canGo[i]])
{
visited[graph.nodes[current-1].canGo[i]] = 2;
graph.cost[graph.nodes[current-1].canGo[i]-1] = graph.cost[current-1] + 1;
enqueue(graph.nodes[current-1].canGo[i]);
}
}
}
}
void print_out(GraphVertex graph)
{
FILE* fptr = fopen("bfs.out", "w");
for (int i = 0; i < graph.numNodes; i++)
fprintf(fptr,"%d ", graph.cost[i]);
fclose(fptr);
}
int main()
{
int source;
GraphVertex graph=readFile("bfs.in", &source);
bfs(graph, source);
print_out(graph);
return 0;
}