📜  用对角线填充的从 1 到 N*N 的整数填充空的 2D 矩阵

📅  最后修改于: 2022-05-13 01:57:24.478000             🧑  作者: Mango

用对角线填充的从 1 到 N*N 的整数填充空的 2D 矩阵

给定一个整数N ,任务是填充一个大小为NxN的矩阵M ,从主对角线开始,然后在上下三角对角线之间交替,以递增的方式使得从1N 2 的每个数字只出现一次。

例子:

Input: N = 4
Output: 
1 8 13 16
5 2 9 14
11 6 3 10
15 12 7 4
Explanation:
First filling the main diagonal:
 1   
    2  
       3 
          4
Next, fill the lower diagonal below the main diagonal
 1 
 5  2  
    6  3 
      7  4
Next, fill the upper diagonal above the main diagonal
 1  8 
 5  2  9 
    6  3 10
       7  4
Following the same pattern and altering between 
upper and lower triangular matrix, 
we get the final matrix as
 1  8 13 16
 5  2  9 14
11  6  3 10
15 12  7  4

Input: N = 3
Output:
1 6 9
4 2 7
8 5 3

处理方法:按照以下步骤解决问题:

  • 将变量cur初始化为1 。这将跟踪当前号码
  • 将变量d初始化为1 。这会跟踪对角线。
  • 使用d1迭代到(N+N-1) 。这是对角线的数量。
    • 如果 d 是偶数,则将两个变量rc分别初始化为d/20
    • 否则,将两个变量rc分别初始化为0d/2
    • 迭代直到rc都小于N
      • 将矩阵M更新为M[r]=cur。
      • 增加currc
    • 退出内循环后,增加d
  • 最后,显示矩阵M

下面是上述方法的实现:

C++
// C++ implementation of the above approach
#include 
using namespace std;
// Function to fill the matrix diagonally alternating
// between upper and lower diagonals
void fillMatrix(int N)
{
    // variables to keep track of
    // diagonals and current number
    int d = 1, cur = 1;
    // Matrix
    int M[N][N];
    // Iterating over all diagonals
    while (d <= 2 * N - 1) {
        int r, c;
        // For lower triangle
        if (d % 2 == 0)
            r = d / 2, c = 0;
        // For upper triangle
        else
            r = 0, c = d / 2;
        // Placing the current number
        // in appropriate position
        while (r < N && c < N) {
            M[r] = cur;
            cur++;
            r++;
            c++;
        }
        d++;
    }
 
    // Displaying the matrix
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            cout << M[i][j] << " ";
        }
        cout << endl;
    }
}
// Driver code
int main()
{
    // Input
    int N = 4;
 
    // Function calling
    fillMatrix(N);
    return 0;
}


Java
// Java implementation of the above approach
 
import java.io.*;
 
class GFG {
    static void fillmatrix(int m[][], int n)
    {
 
        int r, c;
        int num = 1, d = 1;
        // 2*n-1 is no of diagonals
        while (d <= 2 * n - 1) {
            // If d%2==0 switch to
            // lower triangular diagonal
            if (d % 2 == 0) {
                r = d / 2;
                c = 0;
                while (r < n && c < n) {
                    m[r] = num++;
                    r++;
                    c++;
                }
            }
            // If d%2==1 switch to
            // upper triangular diagonal
            else {
                r = 0;
                c = d / 2;
                while (c < n && r < n) {
                    m[r] = num++;
                    r++;
                    c++;
                }
            }
            d++;
        }
    }
    // Utility function to display the matrix
    static void display(int m[][], int n)
    {
        int i, j;
        for (i = 0; i < n; i++) {
            for (j = 0; j < n; j++) {
                System.out.printf(m[i][j] + " ");
            }
            System.out.println();
        }
    }
 
    public static void main(String[] args)
    {
        int n = 4;
        int[][] m = new int[4][4];
        fillmatrix(m, n);
        display(m, n);
    }
}


Python3
# Python3 implementation of the above approach
 
# Function to fill the matrix diagonally
# alternating between upper and lower diagonals
def fillMatrix(N):
     
    # Variables to keep track of
    # diagonals and current number
    d = 1
    cur = 1
     
    # Matrix
    M = [[0 for i in range(N)]
            for i in range(N)]
             
    # Iterating over all diagonals
    while (d <= 2 * N - 1):
        r, c = 0, 0
         
        # For lower triangle
        if (d % 2 == 0):
            r = d // 2
            c = 0
             
        # For upper triangle
        else:
            r = 0
            c = d // 2
             
        # Placing the current number
        # in appropriate position
        while (r < N and c < N):
            M[r] = cur
            cur += 1
            r += 1
            c += 1
 
        d += 1
 
    # Displaying the matrix
    for i in M:
        print(*i)
 
# Driver code
if __name__ == '__main__':
     
    # Input
    N = 4
 
    # Function calling
    fillMatrix(N)
 
# This code is contributed by mohit kumar 29


C#
// C# implementation of the above approach
using System.IO;
using System;
 
class GFG{
     
static void fillmatrix(int[, ] m, int n)
{
    int r, c;
    int num = 1, d = 1;
     
    // 2*n-1 is no of diagonals
    while (d <= 2 * n - 1)
    {
         
        // If d%2==0 switch to
        // lower triangular diagonal
        if (d % 2 == 0)
        {
            r = d / 2;
            c = 0;
            while (r < n && c < n)
            {
                m[r, c] = num++;
                r++;
                c++;
            }
        }
         
        // If d%2==1 switch to
        // upper triangular diagonal
        else
        {
            r = 0;
            c = d / 2;
             
            while (c < n && r < n)
            {
                m[r, c] = num++;
                r++;
                c++;
            }
        }
        d++;
    }
}
 
// Utility function to display the matrix
static void display(int[,] m, int n)
{
    int i, j;
    for(i = 0; i < n; i++)
    {
        for(j = 0; j < n; j++)
        {
            Console.Write(m[i, j] + " ");
        }
        Console.WriteLine();
    }
}
 
// Driver code
static void Main()
{
    int n = 4;
    int[,] m = new int[4, 4];
     
    fillmatrix(m, n);
    display(m, n);
}
}
 
// This code is contributed by abhinavjain194


Javascript


输出

1 8 13 16 
5 2 9 14 
11 6 3 10 
15 12 7 4 

时间复杂度: O(N 2 )
辅助空间: O(1)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程