Reputation:
i have following code from graph theory topics,kruskal algorithm for minimal spanning tree
#include<iostream>
#include<stdlib.h>
using namespace std;
int cost[10][10],i,j,k,n,m,c,visit,visited[10],l,v,count,count1,vst,p;
int main(){
int dup1,dup2;
cout<<" enter number of vertices "<<endl;
cin>>n;
cout<<"enter number of edges "<<endl;
cin>>m;
cout<<" EDGES Cost "<<endl;
for(k=1;k<=m;k++){
cin>>i>>j>>c;
cost[i][j]=c;
cost[j][i]=c;
}
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
if(cost[i][j]==0)
cost[i][j]=31999;
visit=1;
while(visit<n){
v=31999;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(cost[i][j]!=31999 && cost[i][j]<v && cost[i][j]!=-1)
{
int count=0;
for(p=1;p<=n;p++){
if(visited[p]==i || visited[p]==j)
count++;
}
if(count>=2){
for(p=1;p<=n;p++)
if(cost[i][p]!=31999 && p!=j)
dup1=p;
for(p=1;p<=n;p++)
if(cost[j][p]!=31999 && p!=i)
dup2=p;
if(cost[dup1][dup2]==-1)
continue;
}
l=i;
k=j;
v=cost[i][j];
}
cout<<" edgde from "<<l<<" --> "<<k;
cost[l][k]=-1;
cost[k][l]=-1;
visit++;
int count=0;
count1=0;
for(i=1;i<=n;i++)
{
if(visited[i]==1)
count++;
if(visited[i]==k)
count1++;
}
if(count==0)
visited[++vst]=1;
if(count1==0)
visited[++vst]=k;
}
return 0;
}
which works and for following input
1 2 1
2 3 2
3 4 3
1 3 3
where number of vertices and number of edges is 4,gives me output like this
edge from 1–>2edge from 2–>3edge from 1–>3
my question is is there any semantical error?also i have used arrays and many variables,can i make shorted this code?my (programming)language is c++
Upvotes: 0
Views: 9281
Reputation: 1912
User input can easily break this code: If the user gives values equal to or greater than 10 for n or m, you could run off the end of your array.
Upvotes: 2