I am in the midst of applying a bellman ford algorithm using a queue and my code works for all cases where the source vertex is 0 however outputs garbage when the source vertex is changed. I think there must be an issue with the line “for*edge;edge<(n*n);edge);” Thanks.

# include

# include

# include

int readGraphWeighted(int n, int m, int graph[]){ int i; int size = n*n; for(i = 0; i < size; i++){ graph[i] = 0; }

int edgeA; int edgeB; int weight; for(i = 0; i < m; i++){ scanf(“%d %d %d”, &edgeA, &edgeB, &weight); graph[edgeA*n + edgeB] = weight;

} }

int findVal(int element, int queueSize, int queue[]){

`//if element is in the queue then function returns 0 //else it returns 1 int i; int toReturn=1; for(i=0;i<queueSize;i++){ if(element==queue[i]){ toReturn=0; } } return toReturn; `

}

int main(){

`//initialize all necessary int n; int m; scanf("%d %d",&n,&m); int d[n]; int p[n]; int graph[n*n]; int queue[n]; int source; int edge; int queueSize=0; int head=0; //intermediary variables int i; int row; int col; //read in all information needed readGraphWeighted(n,m,graph); scanf("%d",&source); //intialize everything as instructed for(i=0;i<n;i++){ d[i]=INT_MAX; p[i]=-1; queue[i]=0; } queue[head]=source; queueSize++; d[source]=0; p[source]=source; //**main body of program** while(queueSize !=0){ //pop edge=queue[head]; queueSize=queueSize-1; head++; //for every edge for(edge;edge<(n*n);edge){ if(graph[edge] !=0){ //if we reach a value in graph record its row and col row=edge/n; col=edge%n; //if the value in d is larger replace it if(d[col]>d[row]+graph[edge]){ d[col]=d[row]+graph[edge]; //update predecessor p[col]=row; if(findVal(col,queueSize,queue) == 1){ //push queue[queueSize-1]=col; queueSize++; } } } } } printf("\nRESULTS:\nsource vertex: %d\n",source); printf("D: "); for(i=0;i<n;i++){ printf("%d, ",d[i]); } printf("\n"); printf("P: "); for(i=0;i<n;i++){ printf("%d, ",p[i]); } `

}