0

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
}
3
  • 1
    Your indexing is wrong: use graph[i,k,] not graph[i][k]. Commented Jul 4, 2020 at 16:42
  • @user2554330 Thank you. I fixed it but now I am getting: Error in if(..) argument is of length zero. Commented Jul 6, 2020 at 16:08
  • 1
    You were starting indexing at 0, not 1. Commented Jul 6, 2020 at 17:02

1 Answer 1

0
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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.