Pagini recente » Cod sursa (job #2886128) | Cod sursa (job #1981352) | Cod sursa (job #1204482) | Cod sursa (job #2795495) | Cod sursa (job #2741504)
#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 - 1;
int visited[100001] = {0}, cost[100001] = {0};
while (i <= j) {
visited[queue[i]] = 1;
for (int k = 0; k < graph.nodes[queue[i]].numNeighbors; k++) {
if (visited[graph.nodes[queue[i]].neighbors[k]->name] == 0) {
ct = 0;
for (int l = i + 1; l <= j; l++) {
if (queue[l] == graph.nodes[queue[i]].neighbors[k]->name) ct = 1;
}
if (ct == 0) {
queue[++j] = graph.nodes[queue[i]].neighbors[k]->name;
cost[queue[j]] = cost[queue[i]] + 1;
}
}
}
i++;
}
for (i = 0; i < graph.numNodes; i++) {
if (visited[i] == 0) cost[i] = -1;
}
FILE* o = fopen("bfs.out", "w");
if (o == NULL) return;
for (i = 0; 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;
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);
a--;
b--;
if (graph.nodes[a].numNeighbors == 0) {
graph.nodes[a].neighbors = (vertex**)malloc(sizeof(vertex*));
}
graph.nodes[a].neighbors = (vertex**)realloc(graph.nodes[a].neighbors, sizeof(vertex**) * (++graph.nodes[a].numNeighbors));
graph.nodes[a].neighbors[graph.nodes[a].numNeighbors - 1] = &(graph.nodes[b]);
//&(graph.nodes[b]);
}
fclose(f);
return graph;
}
int main()
{
//POINTERS/VERTEX
int start;
graphVertex graphV = readGraphVertex("bfs.in", &start);
bfs(graphV, start);
return 0;
}