📜  Java程序以蛇模式打印矩阵

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

Java程序以蛇模式打印矩阵

给定一个 nxn 矩阵。在给定的矩阵中,您必须以蛇形模式打印矩阵的元素。

例子 :

Input :mat[][] = { {10, 20, 30, 40},
                   {15, 25, 35, 45},
                   {27, 29, 37, 48},
                   {32, 33, 39, 50}};
              
Output : 10 20 30 40 45 35 25 15 27 29
         37 48 50 39 33 32 

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

矩阵印刷

我们遍历所有行。对于每一行,我们检查它是偶数还是奇数。如果是偶数,我们从左到右打印,否则从右到左打印。

Java
// Java program to print matrix in snake order
import java.util.*;
class GFG
{
    static void print(int [][] mat)
    {
        // Traverse through all rows
        for (int i = 0; i < mat.length; i++)
        {
  
            // If current row is even, print from
            // left to right
            if (i % 2 == 0)
            {
                for (int j = 0; j < mat[0].length; j++)
                    System.out.print(mat[i][j] +" ");
  
  
            // If current row is odd, print from
            // right to left
            }
            else
            {
                for (int j = mat[0].length - 1; j >= 0; j--)
                    System.out.print(mat[i][j] +" ");
            }
        }
    }
  
    // Driver code
    public static void main(String[] args)
    {
        int mat[][] = new int[][]
        {
            { 10, 20, 30, 40 },
            { 15, 25, 35, 45 },
            { 27, 29, 37, 48 },
            { 32, 33, 39, 50 }
        };
  
        print(mat);
    }
}
/* This code is contributed by Mr. Somesh Awasthi */


输出 :

10 20 30 40 45 35 25 15 27 29 37 48 50 39 33 32 

请参阅完整文章以蛇模式打印矩阵以获取更多详细信息!