Fill missing entries of a magic square - GeeksforGeeks

28 May, 2021
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 = 15Input: 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 rowSumBelow is the implementation of the above approach:  
C++
Java
Python3
C#
PHP
Javascript
// C++ program to fill blanks with numbers#include <bits/stdc++.h>using namespace std; // Function to print the original matrixint 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 functionint main(){    int sq[3][3] = {        { 0, 7, 6 },        { 9, 0, 1 },        { 4, 3, 0 }    };     printFilledDiagonal(sq);    return 0;}
// Java program to fill blanks with numbers import java.io.*; class GFG {      // Function to print the original matrixstatic 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..
# Python3 program to fill blanks# with numbers # Function to print the original matrixdef 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 Codeif __name__ == "__main__":     sq = [[0, 7, 6],          [9, 0, 1],          [4, 3, 0]]     printFilledDiagonal(sq)     # This code is contributed# by Rituraj Jain
// C# program to fill blanks with numbers using System; class GFG {       // Function to print the original matrixstatic 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
<?php// PHP program to fill blanks with numbers // Function to print the original matrixfunction 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?>
<script>    // Javascript 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        let sum = 0;        for (let i = 0; i < 3; i++)            for (let j = 0; j < 3; j++)                sum += sq[i][j];         // Required sum of each row (from the approach)        sum /= 2;         for (let i = 0; i < 3; i++) {             // Row sum excluding the diagonal element            let rowSum = 0;            for (let 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 (let i = 0; i < 3; i++) {            for (let j = 0; j < 3; j++)                document.write(sq[i][j] + " ");            document.write("</br>");        }        return 0;    }         let sq = [              [ 0, 7, 6 ],              [ 9, 0, 1 ],              [ 4, 3, 0 ]              ];       printFilledDiagonal(sq); </script>
2 7 6 
9 5 1 
4 3 8
 
vt_m
inderDuMCA
rituraj_jain
Akanksha_Rai
decode2207
magic-square
Matrix
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sudoku | Backtracking-7
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
Program to multiply two matrices
Inplace rotate square matrix by 90 degrees | Set 1
Count all possible paths from top left to bottom right of a mXn matrix
Efficiently compute sums of diagonals of a matrix
Printing all solutions in N-Queen Problem
Min Cost Path | DP-6
Python program to multiply two matrices
The Celebrity Problem