I am trying to implement Floyd Warshall's algorithm in R. When I run the programm I get the following error: Error in if ((graph[i][k] + graph[k][j]) < graph[i][j]) { : argument is of length zero
I know this has something to do with the iteration over graph array. What is the right way to iterate over graph array? Thank you.
Graph:
10
(0)------->(3)
| /|\
5 | |
| | 1
\|/ |
(1)------->(2)
3
Code:
inf <- 99999
graph <- array(c(0, inf, inf, inf, 5, 0, inf, inf, inf, 3, 0, inf, 10, inf, 1, 0), dim = c(4, 4, 1))
V <- 4
new.floyd <- function(graph){
k <- 0
i <- 0
j <- 0
while(k < V){
while(i < V){
while(j < V){
if((graph[i][k] + graph[k][j]) < graph[i][j]){
graph[i][j] <- (graph[i][k] + graph[k][j])
}
j <- j + 1
}
j <- 0
i <- i + 1
}
i <- 0
k <- k + 1
}
inf <- 99999
graph <- array(c(0, inf, inf, inf, 5, 0, inf, inf, inf, 3, 0, inf, 10, inf, 1, 0), dim = c(4, 4, 1))
V <- 4
new.floyd <- function(graph){
k <- 1
i <- 1
j <- 1
while(k <= V){
while(i <= V){
while(j <= V){
if((graph[i, k,] + graph[k,j,]) < graph[i,j,]){
graph[i,j,] <- (graph[i,k,] + graph[k,j,])
}
j <- j + 1
}
j <- 1
i <- i + 1
}
i <- 1
k <- k + 1
}
print(graph)
}
new.floyd(graph)