📜  以 Z 形式打印矩阵的Java程序

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

以 Z 形式打印矩阵的Java程序

给定一个 n*n 阶的方阵,我们需要以 Z 形式打印矩阵的元素

Examples:
Input : mat[][] =  {1, 2, 3,
                    4, 5, 6,
                    7, 8, 9}
Output : 1 2 3 5 7 8 9

Input : mat[][] = {5, 19, 8, 7,
                   4, 1, 14, 8,
                   2, 20, 1, 9,
                   1, 2, 55, 4}
Output: 5 19 8 7 14 20 1 2 55 4
// Java program to print a
// square matrix in Z form
  
import java.lang.*;
import java.io.*;
  
class GFG {
    public static void diag(int arr[][], int n)
    {
        int i = 0, j, k;
  
        // print first row
        for (j = 0; j < n - 1; j++) {
            System.out.print(arr[i][j] + " ");
        }
  
        // Print diagonal
        k = 1;
        for (i = 0; i < n - 1; i++) {
            for (j = 0; j < n; j++) {
                if (j == n - k) {
                    System.out.print(arr[i][j] + " ");
                    break;
                }
            }
            k++;
        }
        // Print last row
        i = n - 1;
        for (j = 0; j < n; j++)
            System.out.print(arr[i][j] + " ");
  
        System.out.print("\n");
    }
  
    public static void main(String[] args)
    {
        int a[][] = { { 4, 5, 6, 8 },
                      { 1, 2, 3, 1 },
                      { 7, 8, 9, 4 },
                      { 1, 8, 7, 5 } };
  
        diag(a, 4);
    }
}
// Code contributed by Mohit Gupta_OMG <(0_o)>
输出:
4 5 6 8 3 8 1 8 7 5

有关详细信息,请参阅有关以 Z 形式打印矩阵的程序的完整文章!