Search code examples
c#recursionsum

least sum of vertical line in 2d array


I have a 2D array I have the

number of rows = H
number of columns = W
the 2d array itself = arr
they are all integers

I am tasked to return the lowest sum of the vertical line starts with each point at first row

input

1 2 3
4 5 6
7 8 9

output 12

I thought about a way to solve this by using recursion but i don't get right results.

the function takes the array, the position i want to calculate minimum sum at (should be on the first-row coz it's a line) number of columns and rows and res is to return the sum res is initialized in the main function by arr at row x and column y

I am sure about the idea but the way I am summing is probably wrong

static int Summ(int [,]arr,int x,int y,int W,int H,int res)
    {
        if (x == H - 1)
            res += arr[x, y];
        else
            if (y == 0)
                res += Math.Min(Summ(arr, x + 1, y, W, H, res), Summ(arr, x + 1, y + 1, W, H, res));
            else if (y== W-1)
                res += Math.Min(Summ(arr, x + 1, y, W, H, res), Summ(arr, x + 1, y - 1, W, H, res));
            else 
                res+= res += Math.Min(Math.Min(Summ(arr, x + 1, y, W, H, res), Summ(arr, x + 1, y + 1, W, H, res)),Summ(arr,x+1,y-1,W,H,res));
        return res;
    }

Solution

  • An iterative solution may be simpler:

    static int MinSum(int [,]arr)
    {
        int min = Int32.MaxValue;
    
        for (int j = 0; j < arr.GetLength(1); ++j) 
        {
            int sum = 0;
            for (int i = 0; i < arr.GetLength(0); ++i)
            {
                sum += arr[i, j];
            }
            min = Math.min(min, sum);
        }
    
        return min;
    }
    

    EDIT:
    Given the clarification in the comment below, this solution is not correct.
    Instead, you could iterate over the rows and sum the minimal value in each row:

    static int MinSum(int [,]arr)
    {
        int sum = 0;
    
        for (int i = 0; j < arr.GetLength(0); ++i) 
        {
            int minCol = arr[i, 0];
            for (int j = 1; j < arr.GetLength(1); +_j)
            {
                minCoal = Math.min(minCol, arr[i, j]);
            }
            min += minCol;
        }
    
        return sum;
    }