Click here to Skip to main content
15,885,366 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a problem wherein I'll be given a matrix (say 3*3) with random values. My goal is to balance the matrix in such a way that the row sum, column sum, and diagonal sum must be equal and the solution must be optimized.

and the code I have tried is initially to generate a matrix with equal row sum, column sum, and diagonal sum where sum = 15, but I have to achieve this output

eg: if sum = 15, input matrix is [[8,8,1], [3,4,5], [6,6,2]]
output:
[[8,2,5],[1,4,7],[6,9,3]] 


The cost of changing the values must be minimum and optimized. I am not very sure of the input matrix as well but the goal is to balance the matrix for a given sum

What I have tried:

#include <stdio.h>
//MATRIX O/P NEEDED => [[8,2,5],[1,4,7],[6,9,3]] 
int arr[3][3];
int safe(int row, int col, int num)
{
    for(int i=0;i<col;i++)
    {
        if(arr[row][i]==num)
        {
            return 0;
        }
    }
    for(int i=0;i<row;i++)
    {
        if(arr[i][col]==num)
        {
            return 0;
        }
    }
    return 1;
}

void display(int row, int col)
{
    for(int i=0;i<row;i++,printf("\n"))
    {
        for(int j=0;j<col;j++)
        {
            printf("%d ",arr[i][j]);
        }
    }
}

void solve(int values[], int row, int col, int sum, int tot_row, int tot_col)
{
    if(row==tot_row && col==tot_col)
    {
        display(tot_row, tot_col);
        return;
    }
    else
    {
        for(int i=0;i<(tot_row*tot_col);i++)
        {
            if(safe(row,col,values[i])==1)
            {
                arr[row][col] = values[i];
                solve(values, row+1, col+1, sum, tot_row, tot_col);
                //backtrack
                arr[row][col]=-1;
            }
        }
    }
}

int main()
{
    int r=3;
    int c= 3;
    int sum = 15;
    int total = r*c;
    int values[total];
    for(int i=0;i<r;i++)
    {
        for(int j=0;j<c;j++)
        {
            arr[i][j]=-1;
        }
    }
    for(int i=0;i<(r*c);i++)
    {
        values[i]=i+1;
        // printf("%d ",values[i]);
    }
    
    solve(values, 0, 0, sum, r, c);
    

    return 0;
}
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900