# Function to calculate permanent of a matrix permanent <- function(mat) { n <- nrow(mat) # Number of rows in the matrix p <- 0 # Initialize permanent to 0 permute <- function(col) { # Define a recursive function to calculate permanent if (length(col) == n) { # Base case p <<- p + prod(mat[cbind(1:n, col)]) # Update permanent } else { # Recursive case for (i in setdiff(1:n, col)) { permute(c(col, i)) # Recursively call permute with updated column } } } permute(integer(0)) # Call permute with an empty column to start the recursion return(p) } # Example usage #mat <- matrix(c(1,2,3,4), nrow = 2) #permanent(mat) # Returns 10