Fill missing entries of a magic square

Given a 3X3 matrix mat with it’s left diagonal elements missing (set to 0), considering the sum of every row, column and diagonal of the original matrix was equal, the task is to find the missing diagonal elements and print the original matrix.

Examples:

Input: mat[][] = {{0, 7, 6}, {9, 0, 1}, {4, 3, 0}}
Output:
2 7 6
9 5 1
4 3 8
Row sum = Column sum = Diagonal sum = 15



Input: mat[][] = {{0, 1, 1}, {1, 0, 1}, {1, 1, 0}}
Output:
1 1 1
1 1 1
1 1 1

Approach: Let Sum denote the total sum excluding the diagonal elements,

Sum = total sum of the given matrix – diagonalSum
Sum = (3 * rowSum) – diagonalSum
Sum = (2 * rowSum) [Since, columnSum = rowSum = diagonalSum]
rowSum = Sum / 2

Hence, we can insert an element in every row such that the sum of the row is rowSum

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to fill blanks with numbers
#include <bits/stdc++.h>
using namespace std;
  
// Function to print the original matrix
int printFilledDiagonal(int sq[][3])
{
    // Calculate the sum of all the elements
    // of the matrix
    int sum = 0;
    for (int i = 0; i < 3; i++)
        for (int j = 0; j < 3; j++)
            sum += sq[i][j];
  
    // Required sum of each row (from the approach)
    sum /= 2;
  
    for (int i = 0; i < 3; i++) {
  
        // Row sum excluding the diagonal element
        int rowSum = 0;
        for (int j = 0; j < 3; j++)
            rowSum += sq[i][j];
  
        // Element that must be inserted at
        // diagonal element of the current row
        sq[i][i] = sum - rowSum;
    }
  
    // Print the updated matrix
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++)
            cout << sq[i][j] << " ";
        cout << endl;
    }
}
  
// Driver Program to test above function
int main()
{
    int sq[3][3] = {
        { 0, 7, 6 },
        { 9, 0, 1 },
        { 4, 3, 0 }
    };
  
    printFilledDiagonal(sq);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to fill blanks with numbers
  
import java.io.*;
  
class GFG {
     
  
  
// Function to print the original matrix
static int printFilledDiagonal(int sq[][])
{
    // Calculate the sum of all the elements
    // of the matrix
    int sum = 0;
    for (int i = 0; i < 3; i++)
        for (int j = 0; j < 3; j++)
            sum += sq[i][j];
  
    // Required sum of each row (from the approach)
    sum /= 2;
  
    for (int i = 0; i < 3; i++) {
  
        // Row sum excluding the diagonal element
        int rowSum = 0;
        for (int j = 0; j < 3; j++)
            rowSum += sq[i][j];
  
        // Element that must be inserted at
        // diagonal element of the current row
        sq[i][i] = sum - rowSum;
    }
  
    // Print the updated matrix
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++)
            System.out.print( sq[i][j] + " ");
        System.out.println();
    }
    return 0;
}
  
// Driver Program to test above function
  
    public static void main (String[] args) {
        int sq[][] = {
        { 0, 7, 6 },
        { 9, 0, 1 },
        { 4, 3, 0 }
    };
  
    printFilledDiagonal(sq);
    }
      
}
// This code is contributed by anuj_67..

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to fill blanks 
# with numbers 
  
# Function to print the original matrix 
def printFilledDiagonal(sq): 
  
    # Calculate the sum of all the
    # elements of the matrix 
    Sum = 0
    for i in range(0, 3): 
        for j in range(0, 3): 
            Sum += sq[i][j] 
  
    # Required sum of each 
    # row (from the approach) 
    Sum = Sum//2
  
    for i in range(0, 3): 
  
        # Row sum excluding the 
        # diagonal element 
        rowSum = 0
        for j in range(0, 3): 
            rowSum += sq[i][j] 
  
        # Element that must be inserted 
        # at diagonal element of the
        # current row 
        sq[i][i] = Sum - rowSum 
      
    # Print the updated matrix 
    for i in range(0, 3): 
        for j in range(0, 3): 
            print(sq[i][j], end = " "
        print()
  
# Driver Code
if __name__ == "__main__"
  
    sq = [[0, 7, 6], 
          [9, 0, 1], 
          [4, 3, 0]] 
  
    printFilledDiagonal(sq) 
      
# This code is contributed
# by Rituraj Jain

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to fill blanks with numbers
  
using System;
  
class GFG {
      
  
  
// Function to print the original matrix
static int printFilledDiagonal(int [,]sq)
{
    // Calculate the sum of all the elements
    // of the matrix
    int sum = 0;
    for (int i = 0; i < 3; i++)
        for (int j = 0; j < 3; j++)
            sum += sq[i,j];
  
    // Required sum of each row (from the approach)
    sum /= 2;
  
    for (int i = 0; i < 3; i++) {
  
        // Row sum excluding the diagonal element
        int rowSum = 0;
        for (int j = 0; j < 3; j++)
            rowSum += sq[i,j];
  
        // Element that must be inserted at
        // diagonal element of the current row
        sq[i,i] = sum - rowSum;
    }
  
    // Print the updated matrix
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++)
            Console.Write( sq[i,j] + " ");
            Console.WriteLine();
    }
    return 0;
}
  
// Driver Program to test above function
  
    public static void Main () {
        int [,]sq = {
        { 0, 7, 6 },
        { 9, 0, 1 },
        { 4, 3, 0 }
    };
  
    printFilledDiagonal(sq);
    }
      
}
// This code is contributed by inder_verma

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to fill blanks with numbers
  
// Function to print the original matrix
function printFilledDiagonal($sq)
{
    // Calculate the sum of all the 
    // elements of the matrix
    $sum = 0;
    for ($i = 0; $i < 3; $i++)
        for ($j = 0; $j < 3; $j++)
            $sum += $sq[$i][$j];
  
    // Required sum of each row
    // (from the approach)
    $sum = (int)($sum / 2);
  
    for ($i = 0; $i < 3; $i++)
    {
  
        // Row sum excluding the 
        // diagonal element
        $rowSum = 0;
        for ($j = 0; $j < 3; $j++)
            $rowSum += $sq[$i][$j];
  
        // Element that must be inserted at
        // diagonal element of the current row
        $sq[$i][$i] = $sum - $rowSum;
    }
  
    // Print the updated matrix
    for ($i = 0; $i < 3; $i++) 
    {
        for ($j = 0; $j < 3; $j++)
            echo $sq[$i][$j] . " ";
        echo "\n";
    }
}
  
// Driver Code
$sq = array(array(0, 7, 6),
            array(9, 0, 1),
            array(4, 3, 0));
  
printFilledDiagonal($sq);
  
// This code is contributed 
// by Akanksha Rai
?>

chevron_right


Output:

2 7 6 
9 5 1 
4 3 8


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.





Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.