📌  相关文章
📜  找到一个平方矩阵,使得每一行和每一列中的元素之和为K

📅  最后修改于: 2021-05-04 16:52:59             🧑  作者: Mango

给定两个整数NK ,任务是找到一个N x N方阵,使得每一行和每一列的总和应等于K。注意,可以有多个这样的矩阵。打印其中任何一个。
例子:

方法:一个N x N矩阵,使得每个左对角线元素等于K ,其余元素为0,将满足给定条件。这样,每一行和每一列的元素之和将等于K。
下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to print the
// required matrix
void printMatrix(int n, int k)
{
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
 
            // Print k for the left
            // diagonal elements
            if (i == j)
                cout << k << " ";
 
            // Print 0 for the rest
            else
                cout << "0 ";
        }
        cout << "\n";
    }
}
 
// Driver code
int main()
{
    int n = 3, k = 7;
 
    printMatrix(n, k);
 
    return (0);
}


Java
// Java implementation of the approach
import java.util.*;
 
class GFG
{
 
// Function to print the required matrix
static void printMatrix(int n, int k)
{
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
 
            // Print k for the left
            // diagonal elements
            if (i == j)
                System.out.print(k + " ");
 
            // Print 0 for the rest
            else
                System.out.print("0 ");
        }
        System.out.print("\n");
    }
}
 
// Driver code
public static void main(String[] args)
{
    int n = 3, k = 7;
 
    printMatrix(n, k);
}
}
 
// This code is contributed by Princi Singh


Python3
# Python3 implementation of the approach
 
# Function to print the
# required matrix
def printMatrix(n, k) :
 
    for i in range(n) :
        for j in range(n) :
 
            # Print k for the left
            # diagonal elements
            if (i == j) :
                print(k, end = " ");
 
            # Print 0 for the rest
            else:
                print("0", end = " ");
                 
        print();
 
# Driver code
if __name__ == "__main__" :
 
    n = 3; k = 7;
 
    printMatrix(n, k);
 
# This code is contributed by AnkitRai01


C#
// C# implementation of the approach
using System;
     
class GFG
{
 
// Function to print the required matrix
static void printMatrix(int n, int k)
{
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
 
            // Print k for the left
            // diagonal elements
            if (i == j)
                Console.Write(k + " ");
 
            // Print 0 for the rest
            else
                Console.Write("0 ");
        }
        Console.Write("\n");
    }
}
 
// Driver code
public static void Main(String[] args)
{
    int n = 3, k = 7;
 
    printMatrix(n, k);
}
}
 
// This code is contributed by PrinciRaj1992


Javascript


输出:
7 0 0 
0 7 0 
0 0 7