Я пытаюсь закодировать алгоритм Прима в R для университетского упражнения, я все настроил, но не могу понять, как закодировать реальный алгоритм, просто не решая его вручную каждый шаг.Вот мой код с примером графика:
C<-matrix(0,nrow=7,ncol=7)
C[1,2]<-5 #Manually inputting cost matrix for one way
C[1,3]<-6
C[1,4]<-7
C[2,3]<-2
C[2,5]<-6
C[2,6]<-3
C[4,7]<-5
C[4,6]<-9
C[3,4]<-7
C[6,7]<-7
C[5,6]<-2
for(j in 1:ncol(C)){ #This adds the cost of edges going the opposite ways
for(i in 1:nrow(C)){
C[i,j]<-C[j,i] #Sets the costs of the edges travelling the opposite way
}
}
print(C) #Outputs the final matrix
A<-which(C==0,arr.ind=TRUE)
C[A]<-100 #This finds all the arcs that don't exist and gives them a value of 100 so they are never chosen for this specific example
print(C) #Outputs the new matrix C that is suitable for the algorithm
Prim<-function(C){
tree<-matrix(0,nrow=6,ncol=2) #Creates a solution matrix with minimal cost arcs
P<-which.min(C[1,]) #I'm starting the algorithm from 1 and looking for the minimal cost arc from 1
tree[1,1]<-1
tree[1,2]<-P #P is the vertex that joins to 1 with smallest length, I am adding it to the first row of the tree matrix
vertices<-rep(0,7)
vertices[1]<-1 #Making a list of vertices currently in the set so I can reject arcs that are already included
vertices[2]<-P
Итак, я попробовал, если операторы отклоняют дуги, которые в данный момент находятся в дереве, но это не помогает, так как каждый раз, когда вы добавляете новую нужную вершину, вам нужнопроверить все дуги из новой вершины, чтобы увидеть, включены ли они уже.Любой совет будет оценен.