int main() { int max_vertex, max_edge, start, v1, v2, edge, i, v; vertex graph; if (scanf("%d %d %d", &max_vertex, &max_edge, &start) == 1); graph = (vertex) calloc(sizeof(struct vertex), max_vertex); for (i = 0; i < max_vertex; i++) { graph[i] = newVertex(); } for(i = 0; i < max_edge; i++) { if (scanf("%d %d %d", &v1, &v2, &edge) == 1); insertEnd(&graph[v1 - 1], newlink(&graph[v2 - 1], edge)); } graph[start - 1].distance = 0; graph[start - 1].change = 0; BellmanFord(graph, max_vertex); for(v = 0; v < max_vertex; v++) { if (graph[v].cycle == 1) { printf("I\n"); } else if (graph[v].distance == INT_MAX) { printf("U\n"); } else { printf("%d\n", graph[v].distance); } } return 0; }
void testProgram() { FILE *file1 = fopen("input.in", "r"); FILE *file2 = fopen("output.data", "w"); graph *G = loadGraph(file1); int **testcost = alocateMemoryForCost(G->noOfVertices); int *testpredecesors = allocateMemoryForPredecesors(G->noOfVertices); BellmanFord(G, 0, testcost, testpredecesors); for (int i = 0; i < G->noOfVertices; i++) { fprintf_s(file2, "%d\n", testcost[1][i]); } fclose(file1); fclose(file2); file1 = fopen("output.data", "r"); file2 = fopen("result.txt", "r"); if (compareFiles(file1, file2)) { printf_s("Test succeded!\n"); } else { printf_s("Test failed!\n"); } }
void main()//User interface { cout<<"BELLMAN FORD SHORTEST PATH GRAPH ALGORITHM\n"; int num,edges,source,dest,weight; cout<<"\nEnter the number of NODES in the graph: "; cin>>num; cout<<"\nEnter the number of EDGES in the graph: "; cin>>edges; struct Graph* graph = createGraph(num, edges); cout<<"\nEnter details of the edges: \n"; for(int i=0; i<edges; i++) { cout<<"\nEDGE "<<i+1; cout<<"\nSouce node: "; cin>>graph->edge[i].source; cout<<"Destination node: "; cin>>graph->edge[i].dest; cout<<"Weight: "; cin>>graph->edge[i].weight; } int s; cout<<"\nEnter the starting node: "; cin>>s; cout << "\n\nFollowing are shortest distances to all other nodes from source node "<<s<<": \n"; BellmanFord(graph, s); getch(); }
// Driver program to test above functions int main() { /* Let us create the graph given in above example */ int V = 5; // Number of vertices in graph int E = 8; // Number of edges in graph struct Graph* graph = createGraph(V, E); // add edge 0-1 (or A-B in above figure) graph->edge[0].src = 0; graph->edge[0].dest = 1; graph->edge[0].weight = -1; // add edge 0-2 (or A-C in above figure) graph->edge[1].src = 0; graph->edge[1].dest = 2; graph->edge[1].weight = 4; // add edge 1-2 (or B-C in above figure) graph->edge[2].src = 1; graph->edge[2].dest = 2; graph->edge[2].weight = 3; // add edge 1-3 (or B-D in above figure) graph->edge[3].src = 1; graph->edge[3].dest = 3; graph->edge[3].weight = 2; // add edge 1-4 (or A-E in above figure) graph->edge[4].src = 1; graph->edge[4].dest = 4; graph->edge[4].weight = 2; // add edge 3-2 (or D-C in above figure) graph->edge[5].src = 3; graph->edge[5].dest = 2; graph->edge[5].weight = 5; // add edge 3-1 (or D-B in above figure) graph->edge[6].src = 3; graph->edge[6].dest = 1; graph->edge[6].weight = 1; // add edge 4-3 (or E-D in above figure) graph->edge[7].src = 4; graph->edge[7].dest = 3; graph->edge[7].weight = -3; BellmanFord(graph, 0); system("pause"); return 0; }
void driverProgram(char *inputFile, char *outputFile) { FILE *fin = fopen(inputFile, "r"); FILE *fout = fopen(outputFile, "w"); int source; graph *G = loadGraph(fin); int **cost = alocateMemoryForCost(G->noOfVertices); int *predecesors = allocateMemoryForPredecesors(G->noOfVertices); printf_s("Give the source vertex:"); scanf_s("%d", &source); BellmanFord(G, source, cost, predecesors); for (int i = 0; i < G->noOfVertices; i++) { fprintf_s(fout, "%d\n", cost[1][i]); } while (true) { int destination; printf_s("Give the vertex to which you want to reconstruct the path:"); scanf_s("%d", &destination); if (cost[1][destination] == infinite) { printf_s("there is no path to %d from %d\n", destination, source); } else if (cost[1][destination] == minfinite) { printf_s("it is a negative cycle cannot display path\n"); } else { reconstructPath(source, destination, G, predecesors); } printf_s("Continue? \n1.Yes\n0.No\n"); int dummy; scanf_s("%d",&dummy); if (dummy == 0) { break; } } fclose(fin); fclose(fout); }
int speedTest(graph *G) { int *predecesors = allocateMemoryForPredecesors(G->noOfVertices); int **cost = alocateMemoryForCost(G->noOfVertices); int source, t0, test[10]; int average = 0; printf_s("give the source vertex:"); scanf_s("%d", &source); for (int i = 0; i < 10; i++) { t0 = clock(); BellmanFord(G, source, cost, predecesors); test[i] = clock() - t0; average += test[i]; } return average / 10; }
main() { int F,N,M,W; scanf("%d", &F); while(F--) { scanf("%d%d%d", &N, &M, &W); for (int i = 0; i < M; i++) { scanf("%d%d%d", &path[i].start, &path[i].end, &path[i].len); path[i+M].init(path[i].end, path[i].start, path[i].len); } for (int i = 0; i < W; i++) { scanf("%d%d%d", &wormhole[i].start, &wormhole[i].end, &wormhole[i].len); wormhole[i].len *= -1; } printf("%s\n", (BellmanFord(N,M,W,1)?"YES":"NO")); } }
main(int argc, char * argv[]){ int i = 0; char ch; char fileToOpen[50]; int sourceNode; while (i < graphSize){ graphFromFile.vertices[i].value = i; i++; } for (int i = 0; i < graphSize; i++){ d[i] = 623737; } printf("Insert the file for parsing: \n"); scanf("%s", fileToOpen); //scans the file to open printf("File containing graph: %s\n", fileToOpen); //opens the file FILE * fp; fp = fopen(fileToOpen, "r"); //printf("error2\n"); if (fp == NULL) { printf("Error opening file, does not exist\nPrgram will now exit. . ."); Sleep(2000); return(-1); } else { makeCoolGraphFromFile(fp); //makes a cool weighted graph from the file } fclose(fp); fflush(stdin); printf("Starting from which node?\n"); scanf("%d", &sourceNode); if (cyclic){ printf("Graph is not a DAG so using Bellman-Ford:\n"); BellmanFord(sourceNode); //this runs when a cycle is detected } else { printf("Graph is a DAG so using DAGSP:\n"); DAGSPalg(sourceNode); //this runs when no cycle is detected } }
int main() { int V, E; int s, d, w; printf("Number of Vertices? "); scanf("%d", &V); printf("Number of Edges? "); scanf("%d", &E); struct Graph* graph = createGraph(V, E); printf("\nEnter Edges Below:\n" ); printf("-----------------\n"); for (int i=0; i<E; i++) { printf("Source Vertex: "); scanf("%d", &s); printf("Destination Vertex: "); scanf("%d", &d); printf("Weight: "); scanf("%d", &w); printf("\n"); graph->edge[i].src = s; graph->edge[i].dest = d; graph->edge[i].weight = w; } int start; printf("What is your starting vertex? "); scanf("%d", &start); BellmanFord(graph, start); return 0; }
int main (void) { int i, S; Graph *G = MakeGraph(); printf ("Enter the source node index: "); scanf ("%d", &S); if (S >= G -> NoOfV) return 1; int Check = BellmanFord (G, G -> V[S]); if (Check == 1) { fprintf (stderr, "\nNegative cycle in the graph!"); return 0; } printf ("All data are as follows: \n"); PrintGraphBFS (G); return 0; }
int main() { int graph[maxVertices][maxVertices],size[maxVertices]={0},visited[maxVertices]={0}; int cost[maxVertices][maxVertices]; int vertices,edges,iter,jter; /* vertices represent number of vertices and edges represent number of edges in the graph. */ scanf("%d%d",&vertices,&edges); int vertex1,vertex2,weight; /* Here graph[i][j] represent the weight of edge joining i and j */ for(iter=0;iter<edges;iter++) { scanf("%d%d%d",&vertex1,&vertex2,&weight); assert(vertex1>=0 && vertex1<vertices); assert(vertex2>=0 && vertex2<vertices); graph[vertex1][size[vertex1]] = vertex2; cost[vertex1][size[vertex1]] = weight; size[vertex1]++; } int source; scanf("%d",&source); BellmanFord(graph,cost,size,source,vertices); return 0; }
DistanceMatrix *Johnson(dgraph *g) { assert(g); unsigned int v_id = g->add_vertex(); unsigned int it = 0; for (it = 0; it < g->vsize(); it++) { if (it == v_id) continue; // Adding edge from newly created vertex to all // existing vertices with edge cost 0. g->add_edge(v_id, it, 0); } if (!BellmanFord(g, g->get_vertex(v_id))) { // Return an invalid matrix if Bellman Ford algorithm returns false. // This means there exits a negetive weight cycle. return (new DistanceMatrix(0)); } // If Bellman Ford returns true then d-values of all the vertices contain // shortest distances to all vertices from newly created vertex (v_id). int *h = (int*) calloc(g->vsize(), sizeof(int)); assert(h); for (it = 0; it < g->vsize(); it++) { assert(g->get_vertex(it)); h[it] = g->get_vertex(it)->d; } // Reassign the weights of the edges so that they are non negetive. // w'(u,v) = w(u,v) + h(u) - h(v) for (it = 0; it < g->vsize(); it++) { vertex *u = g->get_vertex(it); assert(u); unsigned int is = 0; for (is = 0; is < u->edges.size(); is++) { assert(u->edges[is]); unsigned int v_index = u->edges[is]->ends[DESTINATION]; vertex *v = g->get_vertex(v_index); assert(v); int new_cost = u->edges[is]->cost + h[it] - h[v_index]; u->edges[is]->cost = new_cost; //g->set_edge_cost(it, u->edges[is]->ends[DESTINATION], new_cost); } } DistanceMatrix *D = new DistanceMatrix(g->vsize()); for (it = 0; it < g->vsize(); it++) { vertex *u = g->get_vertex(it); Dijkstra(g, g->get_vertex(it)); unsigned int is = 0; for (is = 0; is < g->vsize(); is++) { vertex *v = g->get_vertex(is); assert(v); D->SetDistance(it, is, v->d + h[is] - h[it]); } } // Revert back the original edge weights. for (it = 0; it < g->vsize(); it++) { vertex *u = g->get_vertex(it); assert(u); unsigned int is = 0; for (is = 0; is < u->edges.size(); is++) { assert(u->edges[is]); unsigned int v_index = u->edges[is]->ends[DESTINATION]; vertex *v = g->get_vertex(v_index); assert(v); int old_cost = u->edges[is]->cost + h[v_index] - h[it]; u->edges[is]->cost = old_cost; } } //Remove the extra vertex. return D; }
int main () { int algoritmo = 2; /*Dijkstra*/ if (algoritmo == 0) { /* Posição dos vértices (slide 24): */ /* */ /* 1 2 */ /* 0 3 */ /* 5 4 */ /* */ /*Número de vértices: */ int V = 6; /*Inicializando o Grafo direcionado G: */ Graph *G = criar_grafo (V); /*Adicionando as arestas:*/ adicionar_aresta (G, 0, 1, 10); adicionar_aresta (G, 1, 2, 1); adicionar_aresta (G, 2, 3, 2); adicionar_aresta (G, 4, 3, 5); adicionar_aresta (G, 4, 2, 6); adicionar_aresta (G, 2, 4, 4); adicionar_aresta (G, 5, 2, 9); adicionar_aresta (G, 5, 1, 3); adicionar_aresta (G, 1, 5, 2); adicionar_aresta (G, 0, 5, 5); adicionar_aresta (G, 4, 0, 7); adicionar_aresta (G, 5, 4, 2); /*Caminhos mínimos por Dijkstra: */ int source = 0; Dijkstra (G, source); } /*Bellman-Ford*/ else if (algoritmo == 1) { /* Posição dos vértices (slide 51): */ /* */ /* 1 2 */ /* 0 */ /* 4 3 */ /* */ /*Número de vértices: */ int V = 5; /*Inicializando o Grafo direcionado G: */ Graph *G = criar_grafo (V); /*Adicionando as arestas:*/ adicionar_aresta (G, 0, 1, +6); adicionar_aresta (G, 1, 2, +5); adicionar_aresta (G, 2, 1, -2); adicionar_aresta (G, 3, 2, +7); adicionar_aresta (G, 1, 3, -4); adicionar_aresta (G, 4, 2, -3); adicionar_aresta (G, 1, 4, +8); adicionar_aresta (G, 3, 0, +2); adicionar_aresta (G, 0, 4, +7); adicionar_aresta (G, 4, 3, +9); /*Caminhos mínimos por Dijkstra: */ int source = 0; BellmanFord (G, source); } /*Floyd-Warshall*/ else if (algoritmo == 2) { /* Posição dos vértices (slide 70): */ /* */ /* 1 */ /* 0 2 */ /* */ /* 4 3 */ /*Número de vértices: */ int V = 5; /*Inicializando o Grafo direcionado G: */ Graph *G = criar_grafo (V); /*Adicionando as arestas:*/ adicionar_aresta (G, 0, 1, +3); adicionar_aresta (G, 0, 2, +8); adicionar_aresta (G, 0, 4, -4); adicionar_aresta (G, 1, 3, +1); adicionar_aresta (G, 1, 4, +7); adicionar_aresta (G, 2, 1, +4); adicionar_aresta (G, 3, 2, -5); adicionar_aresta (G, 3, 0, +2); adicionar_aresta (G, 4, 3, +6); /*Caminhos mínimos entre todos os pares: */ FloydWarshall (G); } return 0; }
/* * Takes input till we see an EOF. Input lines may be: * 1. V int -- specifies a (new) set of vertices. We assume that the * identities of the vertices are 0..<int>-1. * 2. E {<int,int>,<int,int>...} -- specifies edges in undirected graph * 3. s int int --specifies the origin and end point of a shortest path that user wants to know */ int main() { struct listType **adjList = NULL; /* v is an array. Each entry in the array contains a list of * type struct listType. */ int state = 0; /* To keep track of the current state of our state-machine. * 0 -- means we are ready to read the 1st char of a line. * 1 -- means we have read V, and are looking for # of vertices. * 2 -- means we have read E, and are looking for 1st vert. in edge. * 3 -- means we have read 1st vert of edge, and are looking for 2nd. * 4 -- means we have read s, and looking for origin point the shortest path user wants to know * 5 -- means we have read origin point and looking for the end point */ char c = '\0'; /* Input character */ int nVerts = 0; /* To store # of vertices */ int nEdges = 0; /* to store number of edges in graph*/ int v[4] = {-1}; /* v[0] and v[1] to store two vertices that are to be an edge */ /*v[3] and v[4] to store two vertices that are to be origin and end point of route*/ int in_brace=0; //flag to show if we are in a pair of { } int in_bracket=0; //flag to show if we are in a pair fo < > int init_done=0; //flag to show if the initialization of graph is finished while(scanf("%c", &c) >= 1) { if(state == 0) { if(c == 'V') { freeAllLists(adjList, nVerts); init_done = 0; if(adjList != NULL) { free(adjList); adjList = NULL; } state = 1; nVerts = 0; continue; } else if(c == 'E') { /* Have we read vertices yet? */ if(adjList == NULL) { printf("Error: need \'V\' specification first.\n"); fflush(stdout); skipToNextLineOfInput(); continue; } init_done = 0; bzero(adjList,nVerts*sizeof(struct listType *)); state = 2; continue; } else if(c == 's') { //have we read vertices yet? if(adjList == NULL) { printf("Error: need \'V\' specification first.\n"); fflush(stdout); skipToNextLineOfInput(); continue; } //judge whether vertex and edges have been initiated if(init_done!=1) { printf("Error: specifying edge first.\n"); fflush(stdout); state=2; continue; } state = 4; continue; } else { /* Error! */ printf("Error: Unrecognized command. Rejecting line.\n"); fflush(stdout); skipToNextLineOfInput(); continue; } } else if(state == 1) { if(readInteger(c, &nVerts, 0) < 0) { printf("Error: Erroneous line. Rejecting it.\n"); fflush(stdout); skipToNextLineOfInput(); state = 0; continue; } /* Allocate an nVerts sized array of (struct listType *) */ adjList = (struct listType **)malloc(nVerts * sizeof(struct listType *)); if(adjList == NULL) { printf("Error: malloc() returned null.\n"); fflush(stdout); break; } bzero(adjList, nVerts*sizeof(struct listType *)); state = 0; continue; } else if(state == 2 || state == 3) { //the ',' in '>,<',ignore it,do nothing until next loop if(c==' '||c=='\t') continue; //when '{' appears, in_brace=1 to suggest we are in a { } if(c=='{') { in_brace=1; continue; } //when '}' appears, in_brace=0 to suggest we are out of the { } if(c=='}') { in_brace=0; continue; } //if in_brace=0 and c='\n', we arrive at the end of E command, //so, transfer to state 0 and wait for new command if(in_brace==0&&c=='\n') { init_done=1; //the initialization of graph finishd state=0; continue; } if(in_brace&&c=='<') { in_bracket=1; continue; } if(in_bracket) { //if(readInteger(c, &(v[state - 2]), !(state - 2)) < 0) int t=0; t=readInteger(c,&(v[state-2]), !(state-2)); if(t<0) { printf("Error: Erroneous line. Rejecting it.\n"); fflush(stdout); skipToNextLineOfInput(); state = 0; continue; } if(state == 2) { state = 3; continue; } /* Else -- state == 3 */ if(v[0] == v[1]) { printf("Error: Cannot add self-edge.\n"); fflush(stdout); state = 0; continue; } if(addEdges(v, adjList, nVerts) < 0) { printf("Error: could not add edges.\n"); fflush(stdout); } if(t==1) { in_bracket=0; state=2; continue; } } } else if(state == 4 || state == 5) { int t = readInteger(c, &(v[state - 2]), !(state - 4)); if(t==-1) { printf("Error: command s needs two integers as begin and end point\n"); fflush(stdout); state = 0; continue; } if(t<0) { printf("Error: Erroneous line. Rejecting it.\n"); fflush(stdout); skipToNextLineOfInput(); state = 0; continue; } if(state == 4) { state = 5; continue; } /* Else -- state == 5 */ if(v[2] < 0 || v[3] < 0 || v[2] >= nVerts || v[3] >= nVerts) { /* Error! */ printf("Error: specifying invalid vertex\n"); fflush(stdout); state=0; continue; } //if begin and end are same vertice, obvious result if(v[2] == v[3]) { printf("%d\n",v[2]);fflush(stdout); state = 0; continue; } NodeType *nodes=NULL; nodes=(NodeType *)malloc(sizeof(NodeType)*nVerts); if(nodes == NULL) { printf("Error: malloc() returned NULL.\n"); fflush(stdout); continue; } EdgeType *edges=NULL; edges=(EdgeType *)malloc(sizeof(EdgeType)*(nVerts*(nVerts-1)/2)); if(edges == NULL) { printf("Error: malloc() returned NULL.\n"); fflush(stdout); continue; } //nEdges is the number of edges in the graph nEdges = GenEdge(adjList, nVerts, edges); //tempflag is a flag to show if the begin and end point are exchanged int tempflag=-1; if(v[2]>v[3]) { tempflag=v[2]; v[2]=v[3]; v[3]=tempflag; } //implementing Bellman-Ford algorithm BellmanFord(v[2], nVerts, nEdges, nodes, edges); //finding out the shortest path, if it exists GenPath(nodes, nVerts, v[2], v[3], tempflag); //release this area of memory free(nodes); nodes=NULL; free(edges); edges=NULL; state = 0; continue; } else { /* Weird -- state should never be anything else */ /* Indicates a serious bug in the program */ printf("Error: state == %d unexpected.\n", state); fflush(stdout); break; } } /* We read EOF, or there was some other input that made scanf() fail. * Exit. */ //printf("Exiting...\n"); return 0; }