📜  矩阵的锯齿形(或对角线)遍历

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

矩阵的锯齿形(或对角线)遍历

给定一个二维矩阵,按对角线顺序打印给定矩阵的所有元素。例如,考虑以下 5 X 4 输入矩阵。

例子:

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

上述矩阵的对角打印为

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

另一个例子

对角矩阵



我们强烈建议您在继续解决方案之前单击此处进行练习。

以下是对角线打印的代码。
给定矩阵“matrix[ROW][COL]”的对角线打印在输出中总是有“ROW + COL – 1”行。

C++
// C++ program to print all elements
// of given matrix in diagonal order
#include 
using namespace std;
 
#define ROW 5
#define COL 4
 
// A utility function to find min
// of two integers
int minu(int a, int b)
{
    return (a < b) ? a : b;
}
 
// A utility function to find min
// of three integers
int min(int a, int b, int c)
{
    return minu(minu(a, b), c);
}
 
// A utility function to find
// max of two integers
int max(int a, int b)
{
    return (a > b) ? a : b;
}
 
// The main function that prints given
// matrix in diagonal order
void diagonalOrder(int matrix[][COL])
{
     
    // There will be ROW+COL-1 lines
    // in the output
    for(int line = 1;
            line <= (ROW + COL - 1);
            line++)
    {
         
        /* Get column index of the first element
           in this line of output.
           The index is 0 for first ROW lines and
           line - ROW for remaining lines  */
        int start_col =  max(0, line - ROW);
 
        /* Get count of elements in this line. The
           count of elements is equal to minimum of
           line number, COL-start_col and ROW */
         int count = min(line, (COL - start_col), ROW);
 
        /* Print elements of this line */
        for(int j = 0; j < count; j++)
            cout << setw(5) <<
            matrix[minu(ROW, line) - j - 1][start_col + j];
 
        /* Print elements of next
           diagonal on next line */
        cout << "\n";
    }
}
 
// Utility function to print a matrix
void printMatrix(int matrix[ROW][COL])
{
    for(int i = 0; i < ROW; i++)
    {
        for(int j = 0; j < COL; j++)
            cout << setw(5) << matrix[i][j];
             
        cout << "\n";
    }
}
 
// Driver code
int main()
{
    int M[ROW][COL] = { { 1, 2, 3, 4 },
                        { 5, 6, 7, 8 },
                        { 9, 10, 11, 12 },
                        { 13, 14, 15, 16 },
                        { 17, 18, 19, 20 },};
    cout << "Given matrix is " << endl;
    printMatrix(M);
 
    cout << "\nDiagonal printing of matrix is " << endl;
    diagonalOrder(M);
    return 0;
}
 
// This code is contributed by shubhamsingh10


C
// C program to print all elements
// of given matrix in diagonal order
#include 
 
#define ROW 5
#define COL 4
 
// A utility function to find min of two integers
int minu(int a, int b)
{ return (a < b)? a: b; }
 
// A utility function to find min of three integers
int min(int a, int b, int c)
{ return minu(minu(a, b), c);}
 
// A utility function to find max of two integers
int max(int a, int b)
{ return (a > b)? a: b; }
 
// The main function that prints given matrix in
// diagonal order
void diagonalOrder(int matrix[][COL])
{
    // There will be ROW+COL-1 lines in the output
    for (int line=1; line<=(ROW + COL -1); line++)
    {
        /* Get column index of the first element
           in this line of output.
           The index is 0 for first ROW lines and
           line - ROW for remaining lines  */
        int start_col =  max(0, line-ROW);
 
        /* Get count of elements in this line. The
           count of elements is equal to minimum of
           line number, COL-start_col and ROW */
         int count = min(line, (COL-start_col), ROW);
 
        /* Print elements of this line */
        for (int j=0; j


Java
// Java program to print all elements
// of given matrix in diagonal order
class GFG {
    static final int ROW = 5;
    static final int COL = 4;
 
    // A utility function to find min
    // of two integers
    static int min(int a, int b)
    {
        return (a < b) ? a : b;
    }
 
    // A utility function to find min
    // of three integers
    static int min(int a, int b, int c)
    {
        return min(min(a, b), c);
    }
 
    // A utility function to find max
    // of two integers
    static int max(int a, int b)
    {
         return (a > b) ? a : b;
    }
 
    // The main function that prints given
    // matrix in diagonal order
    static void diagonalOrder(int matrix[][])
    {
 
        // There will be ROW+COL-1 lines in the output
        for (int line = 1;
             line <= (ROW + COL - 1);
             line++) {
 
            // Get column index of the first
            // element in this line of output.
            // The index is 0 for first ROW
            // lines and line - ROW for remaining lines
            int start_col = max(0, line - ROW);
 
            // Get count of elements in this line.
            // The count of elements is equal to
            // minimum of line number, COL-start_col and ROW
            int count = min(line, (COL - start_col),
                            ROW);
 
            // Print elements of this line
            for (int j = 0; j < count; j++)
                System.out.print(matrix[min(ROW, line)
                                        - j- 1][start_col + j]
                                 + " ");
 
            // Print elements of next diagonal on next line
            System.out.println();
        }
    }
 
    // Utility function to print a matrix
    static void printMatrix(int matrix[][])
    {
        for (int i = 0; i < ROW; i++)
        {
            for (int j = 0; j < COL; j++)
                System.out.print(matrix[i][j] + " ");
            System.out.print("\n");
        }
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int M[][] = {
            { 1, 2, 3, 4 },     { 5, 6, 7, 8 },
            { 9, 10, 11, 12 },  { 13, 14, 15, 16 },
            { 17, 18, 19, 20 },
        };
        System.out.print("Given matrix is \n");
        printMatrix(M);
 
        System.out.print(
            "\nDiagonal printing of matrix is \n");
        diagonalOrder(M);
    }
}
// This code is contributed by Anant Agarwal.


Python3
# Python3 program to print all elements
# of given matrix in diagonal order
ROW = 5
COL = 4
 
# Main function that prints given
# matrix in diagonal order
 
 
def diagonalOrder(matrix):
 
    # There will be ROW+COL-1 lines in the output
    for line in range(1, (ROW + COL)):
        # Get column index of the first element
        # in this line of output. The index is 0
        # for first ROW lines and line - ROW for
        # remaining lines
        start_col = max(0, line - ROW)
 
        # Get count of elements in this line.
        # The count of elements is equal to
        # minimum of line number, COL-start_col and ROW
        count = min(line, (COL - start_col), ROW)
 
        # Print elements of this line
        for j in range(0, count):
            print(matrix[min(ROW, line) - j - 1]
                        [start_col + j], end="\t")
 
        print()
 
 
# Utility function to print a matrix
def printMatrix(matrix):
    for i in range(0, ROW):
        for j in range(0, COL):
            print(matrix[i][j], end="\t")
 
        print()
 
 
# Driver Code
M = [[1, 2, 3, 4],
     [5, 6, 7, 8],
     [9, 10, 11, 12],
     [13, 14, 15, 16],
     [17, 18, 19, 20]]
print("Given matrix is ")
printMatrix(M)
 
print("\nDiagonal printing of matrix is ")
diagonalOrder(M)
 
# This code is contributed by Nikita Tiwari.


C#
// C# program to print all elements
// of given matrix in diagonal order
using System;
using static System.Math;
 
class GFG {
 
    static int ROW = 5;
    static int COL = 4;
 
    // The main function that prints given
    // matrix in diagonal order
    static void diagonalOrder(int[, ] matrix)
    {
 
        // There will be ROW+COL-1 lines in the output
        for (int line = 1;
             line <= (ROW + COL - 1);
             line++) {
 
            // Get column index of the first element
            // in this line of output.The index is 0
            // for first ROW lines and line - ROW for
            // remaining lines
            int start_col = Max(0, line - ROW);
 
            // Get count of elements in this line. The
            // count of elements is equal to minimum of
            // line number, COL-start_col and ROW
            int count = Min(line, Math.Min((COL - start_col), ROW));
 
            // Print elements of this line
            for (int j = 0; j < count; j++)
                Console.Write(matrix[Min(ROW, line) - j - 1, start_col + j] + " ");
 
            // Print elements of next diagonal
            // on next line
            Console.WriteLine();
        }
    }
 
    // Utility function to print a matrix
    static void printMatrix(int[, ] matrix)
    {
        for (int i = 0; i < ROW; i++)
        {
            for (int j = 0; j < COL; j++)
                Console.Write(matrix[i, j] + " ");
 
            Console.WriteLine("\n");
        }
    }
 
    // Driver code
    public static void Main()
    {
        int[, ] M = { { 1, 2, 3, 4 },
                      { 5, 6, 7, 8 },
                      { 9, 10, 11, 12 },
                      { 13, 14, 15, 16 },
                      { 17, 18, 19, 20 } };
 
        Console.Write("Given matrix is \n");
         
        printMatrix(M);
 
        Console.Write("\nDiagonal printing" + " of matrix is \n");
 
        diagonalOrder(M);
    }
}
 
// This code is contributed by Sam007.


PHP


Javascript


C++
#include 
#define R 5
#define C 4
using namespace std;
 
bool isValid(int i, int j)
{
    if (i < 0 || i >= R
        || j >= C || j < 0)
        return false;
    return true;
}
 
void diagonalOrder(int arr[][C])
{
    /* through this for loop we choose
       each element of first column as
       starting point and print diagonal
       starting at it.
    arr[0][0], arr[1][0]....arr[R-1][0]
    are all starting points */
    for (int k = 0; k < R; k++)
    {
        cout << arr[k][0] << " ";
       
        // set row index for next point in
        // diagonal
        int i = k - 1;
        
        // set column index for next point in
        //    diagonal
        int j = 1;
 
        /* Print Diagonally upward */
        while (isValid(i, j)) {
            cout << arr[i][j] << " ";
            i--;
           
            // move in upright direction
            j++;
        }
        cout << endl;
    }
 
    /* through this for loop we choose
       each element of last row as starting
       point (except the [0][c-1] it has
       already been processed in previous
       for loop) and print diagonal starting
       at it. arr[R-1][0], arr[R-1][1]....arr[R-1][c-1]
       are all starting points
     */
 
    // Note : we start from k = 1 to C-1;
    for (int k = 1; k < C; k++)
    {
        cout << arr[R - 1][k] << " ";
       
        // set row index for next point in
        // diagonal
        int i = R - 2;
         
        // set column index for next point in
        // diagonal
        int j = k + 1;
 
        /* Print Diagonally upward */
        while (isValid(i, j))
        {
            cout << arr[i][j] << " ";
            i--;
           
            // move in upright direction
            j++;
        }
        cout << endl;
    }
}
 
// Driver Code
int main()
{
 
    int arr[][C] = {
        { 1, 2, 3, 4 },    
        { 5, 6, 7, 8 },
        { 9, 10, 11, 12 }, 
        { 13, 14, 15, 16 },
        { 17, 18, 19, 20 },
    };
    diagonalOrder(arr);
    return 0;
}


Java
// JAVA Code for Zigzag (or diagonal)
// traversal of Matrix
 
class GFG {
 
    public static int R, C;
 
    private static void diagonalOrder(int[][] arr)
    {
 
        /* through this for loop we choose each
        element of first column as starting point
        and print diagonal starting at it. arr[0][0],
        arr[1][0]....arr[R-1][0] are all starting points */
        for (int k = 0; k < R; k++) {
            System.out.print(arr[k][0] + " ");
 
            // set row index for next
            // point in diagonal
            int i = k - 1;
           
            //  set column index for
            // next point in diagonal
            int j = 1;
 
            /* Print Diagonally upward */
            while (isValid(i, j))
            {
                System.out.print(arr[i][j] + " ");
 
                i--;
                
                // move in upright direction
                j++;
            }
 
            System.out.println("");
        }
 
        /* through this for loop we choose each element
           of last row as starting point (except the
           [0][c-1] it has already been processed in
           previous for loop) and print diagonal
           starting at it. arr[R-1][0], arr[R-1][1]....
           arr[R-1][c-1] are all starting points */
 
        // Note : we start from k = 1 to C-1;
        for (int k = 1; k < C; k++) {
            System.out.print(arr[R - 1][k] + " ");
 
            // set row index for next
            // point in diagonal
            int i = R - 2;
           
            // set column index for
            // next point in diagonal
            int j = k + 1;
 
            /* Print Diagonally upward */
            while (isValid(i, j))
            {
                System.out.print(arr[i][j] + " ");
 
                // move in upright direction
                i--;
                j++;
            }
 
            System.out.println("");
        }
    }
 
    public static boolean isValid(int i, int j)
    {
        if (i < 0 || i >= R
            || j >= C || j < 0)
            return false;
        return true;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int arr[][] = {
            { 1, 2, 3, 4 },    
            { 5, 6, 7, 8 },
            { 9, 10, 11, 12 }, 
            { 13, 14, 15, 16 },
            { 17, 18, 19, 20 },
        };
 
        R = arr.length;
        C = arr[0].length;
 
        // Function call
        diagonalOrder(arr);
    }
}
 
// This code is contributed by Arnav Kr. Mandal.


Python3
# Python3 program to print all elements
# of given matrix in diagonal order
R = 5
C = 4
 
 
def isValid(i, j):
    if (i < 0 or i >= R or j >= C or j < 0):
        return False
    return True
 
 
def diagonalOrder(arr):
 
    # through this for loop we choose each element
    # of first column as starting point and print
    # diagonal starting at it.
    # arr[0][0], arr[1][0]....arr[R-1][0]
    # are all starting points
    for k in range(0, R):
        print(arr[k][0], end="  ")
 
        # set row index for next point in diagonal
        i = k - 1
 
        # set column index for next point in diagonal
        j = 1
 
        # Print Diagonally upward
        while (isValid(i, j)):
            print(arr[i][j], end="  ")
            i -= 1
            j += 1  # move in upright direction
 
        print()
 
    # Through this for loop we choose each
    # element of last row as starting point
    # (except the [0][c-1] it has already been
    # processed in previous for loop) and print
    # diagonal starting at it.
    # arr[R-1][0], arr[R-1][1]....arr[R-1][c-1]
    # are all starting points
 
    # Note : we start from k = 1 to C-1;
    for k in range(1, C):
        print(arr[R-1][k], end="  ")
 
        # set row index for next point in diagonal
        i = R - 2
 
        # set column index for next point in diagonal
        j = k + 1
 
        # Print Diagonally upward
        while (isValid(i, j)):
            print(arr[i][j], end="  ")
            i -= 1
            j += 1  # move in upright direction
 
        print()
 
 
# Driver Code
arr = [[1, 2, 3, 4],
       [5, 6, 7, 8],
       [9, 10, 11, 12],
       [13, 14, 15, 16],
       [17, 18, 19, 20]]
 
# Function call
diagonalOrder(arr)
 
# This code is contributed by Nikita Tiwari.


C#
// C# Code for Zigzag (or diagonal)
// traversal of Matrix
using System;
 
class GFG {
    public static int R, C;
 
    private static void diagonalOrder(int[, ] arr)
    {
 
        /* through this for loop we
        choose each element of first
        column as starting point and
        print diagonal starting at it.
        arr[0,0], arr[1,0]....arr[R-1,0]
        are all starting points */
        for (int k = 0; k < R; k++)
        {
            Console.Write(arr[k, 0] + " ");
 
            // set row index for next
            // point in diagonal
            int i = k - 1;
           
            // set column index for
            // next point in diagonal
            int j = 1;
 
            /* Print Diagonally upward */
            while (isValid(i, j))
            {
                Console.Write(arr[i, j] + " ");
 
                i--;
               
                // move in upright direction
                j++;
            }
 
            Console.Write("\n");
        }
 
        /*  through this for loop we
            choose each element of last
            row as starting point (except
            the [0][c-1] it has already
            been processed in previous for
            loop) and print diagonal starting
            at it. arr[R-1,0], arr[R-1,1]....
            arr[R-1,c-1] are all starting points */
 
        // Note : we start from k = 1 to C-1;
        for (int k = 1; k < C; k++)
        {
            Console.Write(arr[R - 1, k] + " ");
 
            // set row index for next
            // point in diagonal
            int i = R - 2;
           
            // set column index for
            // next point in diagonal
            int j = k + 1;
 
            /* Print Diagonally upward */
            while (isValid(i, j))
            {
                Console.Write(arr[i, j] + " ");
 
                i--;
                j++; // move in upright direction
            }
 
            Console.Write("\n");
        }
    }
 
    public static bool isValid(int i, int j)
    {
        if (i < 0 || i >= R || j >= C || j < 0)
            return false;
        return true;
    }
 
    // Driver code
    public static void Main()
    {
        int[, ] arr = { { 1, 2, 3, 4 },
                        { 5, 6, 7, 8 },
                        { 9, 10, 11, 12 },
                        { 13, 14, 15, 16 },
                        { 17, 18, 19, 20 } };
 
        R = arr.GetLength(0);
        C = arr.GetLength(1);
 
        // Function call
        diagonalOrder(arr);
    }
}
 
// This code is contributed
// by ChitraNayal


PHP
= R ||
        $j >= C || $j < 0) return false;
    return true;
}
 
function diagonalOrder(&$arr)
{
    /* through this for loop we choose
    each element of first column as
    starting point and print diagonal 
    starting at it.
    arr[0][0], arr[1][0]....arr[R-1][0]
    are all starting points */
    for ($k = 0; $k < R; $k++)
    {
        echo $arr[$k][0] . " ";
        $i = $k - 1; // set row index for next
                     // point in diagonal
        $j = 1; // set column index for next
                // point in diagonal
 
        /* Print Diagonally upward */
        while (isValid($i,$j))
        {
            echo $arr[$i][$j] . " ";
            $i--;
            $j++; // move in upright direction
        }
        echo "\n";
    }
 
    /* through this for loop we choose each
    element of last row as starting point
    (except the [0][c-1] it has already been
    processed in previous for loop) and print
    diagonal starting at it. arr[R-1][0],
    arr[R-1][1]....arr[R-1][c-1] are all
    starting points */
 
    //Note : we start from k = 1 to C-1;
    for ($k = 1; $k < C; $k++)
    {
        echo $arr[R - 1][$k] . " ";
        $i = R - 2; // set row index for next
                    // point in diagonal
        $j = $k + 1; // set column index for next
                     // point in diagonal
 
        /* Print Diagonally upward */
        while (isValid($i, $j))
        {
            echo $arr[$i][$j] . " ";
            $i--;
            $j++; // move in upright direction
        }
        echo "\n";
    }
}
 
// Driver Code
$arr = array(array(1, 2, 3, 4),
             array(5, 6, 7, 8),
             array(9, 10, 11, 12),
             array(13, 14, 15, 16),
             array(17, 18, 19, 20));
 
// Function call
diagonalOrder($arr);
 
// This code is contributed
// by rathbhupendra
?>


Javascript


C++
#include 
#define R 5
#define C 4
using namespace std;
 
void diagonalOrder(int arr[][C],
                   int n, int m)
{
    // we will use a 2D vector to
    // store the diagonals of our array
    // the 2D vector will have (n+m-1)
    // rows that is equal to the number of
    // diagonals
    vector > ans(n + m - 1);
 
    for (int i = 0; i < m; i++)
    {
        for (int j = 0; j < n; j++)
        {
            ans[i + j].push_back(arr[j][i]);
        }
    }
 
    for (int i = 0; i < ans.size(); i++)
    {
        for (int j = 0; j < ans[i].size(); j++)
            cout << ans[i][j] << " ";
 
        cout << endl;
    }
}
 
// Driver Code
int main()
{
    // we have a matrix of n rows
    // and m columns
    int n = 5, m = 4;
    int arr[][C] = {
        { 1, 2, 3, 4 },
        { 5, 6, 7, 8 },
        { 9, 10, 11, 12 },
        { 13, 14, 15, 16 },
        { 17, 18, 19, 20 },
    };
    
    // Function call
    diagonalOrder(arr, n, m);
    return 0;
}


Java
import java.util.*;
import java.io.*;
 
class GFG
{
  public static int R = 5, C = 4;
  public static void diagonalOrder(int[][] arr, int n, int m)
  {
 
    // we will use a 2D vector to
    // store the diagonals of our array
    // the 2D vector will have (n+m-1)
    // rows that is equal to the number of
    // diagonals
    ArrayList> ans = new ArrayList>(n+m-1);
    for(int i = 0; i < n + m - 1; i++)
    {
      ans.add(new ArrayList());
    }
 
    for (int i = 0; i < n; i++)
    {
      for (int j = 0; j < m; j++)
      {
        (ans.get(i+j)).add(arr[i][j]);
      }
    }
 
    for (int i = 0; i < ans.size(); i++)
    {
      for (int j = ans.get(i).size() - 1; j >= 0; j--)
      {    System.out.print(ans.get(i).get(j)+ " ");
      }  
      System.out.println();
    }
  }
 
  // Driver code
  public static void main (String[] args) {
    int n = 5, m = 4;
    int[][] arr={
      { 1, 2, 3, 4 },
      { 5, 6, 7, 8 },
      { 9, 10, 11, 12 },
      { 13, 14, 15, 16 },
      { 17, 18, 19, 20 },
    };
 
    // Function call
    diagonalOrder(arr, n, m);
  }
}
 
// This code is contributed by Manu Pathria


Python3
R = 5
C = 5
def diagonalOrder(arr, n, m):
     
    # we will use a 2D vector to
    # store the diagonals of our array
    # the 2D vector will have (n+m-1)
    # rows that is equal to the number of
    # diagonals
    ans = [[] for i in range(n + m - 1)]
     
    for i in range(m):
        for j in range(n):
            ans[i + j].append(arr[j][i])
     
    for i in range(len(ans)):
        for j in range(len(ans[i])):
            print(ans[i][j], end = " ")
        print()
 
# Driver Code
# we have a matrix of n rows
# and m columns
n = 5
m = 4
 
# Function call
arr = [[1, 2, 3, 4],[ 5, 6, 7, 8],[9, 10, 11, 12 ],[13, 14, 15, 16 ],[ 17, 18, 19, 20]]
diagonalOrder(arr, n, m)
 
# This code is contributed by rag2127


C#
using System;
using System.Collections.Generic;
 
public class GFG
{
 
  public static int R = 5, C = 4;
  public static void diagonalOrder(int[,] arr, int n, int m)
  {
 
    // we will use a 2D vector to
    // store the diagonals of our array
    // the 2D vector will have (n+m-1)
    // rows that is equal to the number of
    // diagonals
    List> ans = new List>(n+m-1);
    for(int i = 0; i < n + m - 1; i++)
    {
      ans.Add(new List());
    }
 
    for (int i = 0; i < n; i++)
    {
      for (int j = 0; j < m; j++)
      {
        (ans[i + j]).Add(arr[i, j]);
      }
    }
 
    for (int i = 0; i < ans.Count; i++)
    {
      for (int j = ans[i].Count - 1; j >= 0; j--)
      {   
        Console.Write(ans[i][j] + " ");
      }  
      Console.WriteLine();
    }
 
  }
  // Driver code
  static public void Main ()
  {
    int n = 5, m = 4;
    int[,] arr={
      { 1, 2, 3, 4 },
      { 5, 6, 7, 8 },
      { 9, 10, 11, 12 },
      { 13, 14, 15, 16 },
      { 17, 18, 19, 20 },
    };
 
    // Function call
    diagonalOrder(arr, n, m);
  }
}
 
// This code is contributed by avanitrachhadiya2155


输出
Given matrix is 
    1     2     3     4 
    5     6     7     8 
    9    10    11    12 
   13    14    15    16 
   17    18    19    20 

Diagonal printing of matrix is 
    1 
    5     2 
    9     6     3 
   13    10     7     4 
   17    14    11     8 
   18    15    12 
   19    16 
   20 

下面是解决上述问题的替代方法

Matrix =>       1     2     3     4
                5     6     7     8
                9     10    11   12
                13    14    15   16
                17    18    19   20 
   
Observe the sequence
          1 /  2 /  3 /  4
           / 5  /  6 /  7 /  8
               /  9 / 10 / 11 / 12
                   / 13 / 14 / 15 / 16
                       / 17 / 18 / 19 / 20

C++

#include 
#define R 5
#define C 4
using namespace std;
 
bool isValid(int i, int j)
{
    if (i < 0 || i >= R
        || j >= C || j < 0)
        return false;
    return true;
}
 
void diagonalOrder(int arr[][C])
{
    /* through this for loop we choose
       each element of first column as
       starting point and print diagonal
       starting at it.
    arr[0][0], arr[1][0]....arr[R-1][0]
    are all starting points */
    for (int k = 0; k < R; k++)
    {
        cout << arr[k][0] << " ";
       
        // set row index for next point in
        // diagonal
        int i = k - 1;
        
        // set column index for next point in
        //    diagonal
        int j = 1;
 
        /* Print Diagonally upward */
        while (isValid(i, j)) {
            cout << arr[i][j] << " ";
            i--;
           
            // move in upright direction
            j++;
        }
        cout << endl;
    }
 
    /* through this for loop we choose
       each element of last row as starting
       point (except the [0][c-1] it has
       already been processed in previous
       for loop) and print diagonal starting
       at it. arr[R-1][0], arr[R-1][1]....arr[R-1][c-1]
       are all starting points
     */
 
    // Note : we start from k = 1 to C-1;
    for (int k = 1; k < C; k++)
    {
        cout << arr[R - 1][k] << " ";
       
        // set row index for next point in
        // diagonal
        int i = R - 2;
         
        // set column index for next point in
        // diagonal
        int j = k + 1;
 
        /* Print Diagonally upward */
        while (isValid(i, j))
        {
            cout << arr[i][j] << " ";
            i--;
           
            // move in upright direction
            j++;
        }
        cout << endl;
    }
}
 
// Driver Code
int main()
{
 
    int arr[][C] = {
        { 1, 2, 3, 4 },    
        { 5, 6, 7, 8 },
        { 9, 10, 11, 12 }, 
        { 13, 14, 15, 16 },
        { 17, 18, 19, 20 },
    };
    diagonalOrder(arr);
    return 0;
}

Java

// JAVA Code for Zigzag (or diagonal)
// traversal of Matrix
 
class GFG {
 
    public static int R, C;
 
    private static void diagonalOrder(int[][] arr)
    {
 
        /* through this for loop we choose each
        element of first column as starting point
        and print diagonal starting at it. arr[0][0],
        arr[1][0]....arr[R-1][0] are all starting points */
        for (int k = 0; k < R; k++) {
            System.out.print(arr[k][0] + " ");
 
            // set row index for next
            // point in diagonal
            int i = k - 1;
           
            //  set column index for
            // next point in diagonal
            int j = 1;
 
            /* Print Diagonally upward */
            while (isValid(i, j))
            {
                System.out.print(arr[i][j] + " ");
 
                i--;
                
                // move in upright direction
                j++;
            }
 
            System.out.println("");
        }
 
        /* through this for loop we choose each element
           of last row as starting point (except the
           [0][c-1] it has already been processed in
           previous for loop) and print diagonal
           starting at it. arr[R-1][0], arr[R-1][1]....
           arr[R-1][c-1] are all starting points */
 
        // Note : we start from k = 1 to C-1;
        for (int k = 1; k < C; k++) {
            System.out.print(arr[R - 1][k] + " ");
 
            // set row index for next
            // point in diagonal
            int i = R - 2;
           
            // set column index for
            // next point in diagonal
            int j = k + 1;
 
            /* Print Diagonally upward */
            while (isValid(i, j))
            {
                System.out.print(arr[i][j] + " ");
 
                // move in upright direction
                i--;
                j++;
            }
 
            System.out.println("");
        }
    }
 
    public static boolean isValid(int i, int j)
    {
        if (i < 0 || i >= R
            || j >= C || j < 0)
            return false;
        return true;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int arr[][] = {
            { 1, 2, 3, 4 },    
            { 5, 6, 7, 8 },
            { 9, 10, 11, 12 }, 
            { 13, 14, 15, 16 },
            { 17, 18, 19, 20 },
        };
 
        R = arr.length;
        C = arr[0].length;
 
        // Function call
        diagonalOrder(arr);
    }
}
 
// This code is contributed by Arnav Kr. Mandal.

蟒蛇3

# Python3 program to print all elements
# of given matrix in diagonal order
R = 5
C = 4
 
 
def isValid(i, j):
    if (i < 0 or i >= R or j >= C or j < 0):
        return False
    return True
 
 
def diagonalOrder(arr):
 
    # through this for loop we choose each element
    # of first column as starting point and print
    # diagonal starting at it.
    # arr[0][0], arr[1][0]....arr[R-1][0]
    # are all starting points
    for k in range(0, R):
        print(arr[k][0], end="  ")
 
        # set row index for next point in diagonal
        i = k - 1
 
        # set column index for next point in diagonal
        j = 1
 
        # Print Diagonally upward
        while (isValid(i, j)):
            print(arr[i][j], end="  ")
            i -= 1
            j += 1  # move in upright direction
 
        print()
 
    # Through this for loop we choose each
    # element of last row as starting point
    # (except the [0][c-1] it has already been
    # processed in previous for loop) and print
    # diagonal starting at it.
    # arr[R-1][0], arr[R-1][1]....arr[R-1][c-1]
    # are all starting points
 
    # Note : we start from k = 1 to C-1;
    for k in range(1, C):
        print(arr[R-1][k], end="  ")
 
        # set row index for next point in diagonal
        i = R - 2
 
        # set column index for next point in diagonal
        j = k + 1
 
        # Print Diagonally upward
        while (isValid(i, j)):
            print(arr[i][j], end="  ")
            i -= 1
            j += 1  # move in upright direction
 
        print()
 
 
# Driver Code
arr = [[1, 2, 3, 4],
       [5, 6, 7, 8],
       [9, 10, 11, 12],
       [13, 14, 15, 16],
       [17, 18, 19, 20]]
 
# Function call
diagonalOrder(arr)
 
# This code is contributed by Nikita Tiwari.

C#

// C# Code for Zigzag (or diagonal)
// traversal of Matrix
using System;
 
class GFG {
    public static int R, C;
 
    private static void diagonalOrder(int[, ] arr)
    {
 
        /* through this for loop we
        choose each element of first
        column as starting point and
        print diagonal starting at it.
        arr[0,0], arr[1,0]....arr[R-1,0]
        are all starting points */
        for (int k = 0; k < R; k++)
        {
            Console.Write(arr[k, 0] + " ");
 
            // set row index for next
            // point in diagonal
            int i = k - 1;
           
            // set column index for
            // next point in diagonal
            int j = 1;
 
            /* Print Diagonally upward */
            while (isValid(i, j))
            {
                Console.Write(arr[i, j] + " ");
 
                i--;
               
                // move in upright direction
                j++;
            }
 
            Console.Write("\n");
        }
 
        /*  through this for loop we
            choose each element of last
            row as starting point (except
            the [0][c-1] it has already
            been processed in previous for
            loop) and print diagonal starting
            at it. arr[R-1,0], arr[R-1,1]....
            arr[R-1,c-1] are all starting points */
 
        // Note : we start from k = 1 to C-1;
        for (int k = 1; k < C; k++)
        {
            Console.Write(arr[R - 1, k] + " ");
 
            // set row index for next
            // point in diagonal
            int i = R - 2;
           
            // set column index for
            // next point in diagonal
            int j = k + 1;
 
            /* Print Diagonally upward */
            while (isValid(i, j))
            {
                Console.Write(arr[i, j] + " ");
 
                i--;
                j++; // move in upright direction
            }
 
            Console.Write("\n");
        }
    }
 
    public static bool isValid(int i, int j)
    {
        if (i < 0 || i >= R || j >= C || j < 0)
            return false;
        return true;
    }
 
    // Driver code
    public static void Main()
    {
        int[, ] arr = { { 1, 2, 3, 4 },
                        { 5, 6, 7, 8 },
                        { 9, 10, 11, 12 },
                        { 13, 14, 15, 16 },
                        { 17, 18, 19, 20 } };
 
        R = arr.GetLength(0);
        C = arr.GetLength(1);
 
        // Function call
        diagonalOrder(arr);
    }
}
 
// This code is contributed
// by ChitraNayal

PHP

= R ||
        $j >= C || $j < 0) return false;
    return true;
}
 
function diagonalOrder(&$arr)
{
    /* through this for loop we choose
    each element of first column as
    starting point and print diagonal 
    starting at it.
    arr[0][0], arr[1][0]....arr[R-1][0]
    are all starting points */
    for ($k = 0; $k < R; $k++)
    {
        echo $arr[$k][0] . " ";
        $i = $k - 1; // set row index for next
                     // point in diagonal
        $j = 1; // set column index for next
                // point in diagonal
 
        /* Print Diagonally upward */
        while (isValid($i,$j))
        {
            echo $arr[$i][$j] . " ";
            $i--;
            $j++; // move in upright direction
        }
        echo "\n";
    }
 
    /* through this for loop we choose each
    element of last row as starting point
    (except the [0][c-1] it has already been
    processed in previous for loop) and print
    diagonal starting at it. arr[R-1][0],
    arr[R-1][1]....arr[R-1][c-1] are all
    starting points */
 
    //Note : we start from k = 1 to C-1;
    for ($k = 1; $k < C; $k++)
    {
        echo $arr[R - 1][$k] . " ";
        $i = R - 2; // set row index for next
                    // point in diagonal
        $j = $k + 1; // set column index for next
                     // point in diagonal
 
        /* Print Diagonally upward */
        while (isValid($i, $j))
        {
            echo $arr[$i][$j] . " ";
            $i--;
            $j++; // move in upright direction
        }
        echo "\n";
    }
}
 
// Driver Code
$arr = array(array(1, 2, 3, 4),
             array(5, 6, 7, 8),
             array(9, 10, 11, 12),
             array(13, 14, 15, 16),
             array(17, 18, 19, 20));
 
// Function call
diagonalOrder($arr);
 
// This code is contributed
// by rathbhupendra
?>

Javascript


输出
1 
5 2 
9 6 3 
13 10 7 4 
17 14 11 8 
18 15 12 
19 16 
20 

感谢 Gaurav Ahirwar 提出这种方法。

  • 以抗螺旋形式打印矩阵
  • 以螺旋形式打印矩阵
  • 以锯齿形打印给定矩阵

另一种方法:

敏锐的观察发现,作为数组索引的 [i+j] 的总和在整个对角线上保持不变。所以我们将利用矩阵的这个特性来使我们的代码简短而简单。

下面是上述想法的实现:

C++

#include 
#define R 5
#define C 4
using namespace std;
 
void diagonalOrder(int arr[][C],
                   int n, int m)
{
    // we will use a 2D vector to
    // store the diagonals of our array
    // the 2D vector will have (n+m-1)
    // rows that is equal to the number of
    // diagonals
    vector > ans(n + m - 1);
 
    for (int i = 0; i < m; i++)
    {
        for (int j = 0; j < n; j++)
        {
            ans[i + j].push_back(arr[j][i]);
        }
    }
 
    for (int i = 0; i < ans.size(); i++)
    {
        for (int j = 0; j < ans[i].size(); j++)
            cout << ans[i][j] << " ";
 
        cout << endl;
    }
}
 
// Driver Code
int main()
{
    // we have a matrix of n rows
    // and m columns
    int n = 5, m = 4;
    int arr[][C] = {
        { 1, 2, 3, 4 },
        { 5, 6, 7, 8 },
        { 9, 10, 11, 12 },
        { 13, 14, 15, 16 },
        { 17, 18, 19, 20 },
    };
    
    // Function call
    diagonalOrder(arr, n, m);
    return 0;
}

Java

import java.util.*;
import java.io.*;
 
class GFG
{
  public static int R = 5, C = 4;
  public static void diagonalOrder(int[][] arr, int n, int m)
  {
 
    // we will use a 2D vector to
    // store the diagonals of our array
    // the 2D vector will have (n+m-1)
    // rows that is equal to the number of
    // diagonals
    ArrayList> ans = new ArrayList>(n+m-1);
    for(int i = 0; i < n + m - 1; i++)
    {
      ans.add(new ArrayList());
    }
 
    for (int i = 0; i < n; i++)
    {
      for (int j = 0; j < m; j++)
      {
        (ans.get(i+j)).add(arr[i][j]);
      }
    }
 
    for (int i = 0; i < ans.size(); i++)
    {
      for (int j = ans.get(i).size() - 1; j >= 0; j--)
      {    System.out.print(ans.get(i).get(j)+ " ");
      }  
      System.out.println();
    }
  }
 
  // Driver code
  public static void main (String[] args) {
    int n = 5, m = 4;
    int[][] arr={
      { 1, 2, 3, 4 },
      { 5, 6, 7, 8 },
      { 9, 10, 11, 12 },
      { 13, 14, 15, 16 },
      { 17, 18, 19, 20 },
    };
 
    // Function call
    diagonalOrder(arr, n, m);
  }
}
 
// This code is contributed by Manu Pathria

蟒蛇3

R = 5
C = 5
def diagonalOrder(arr, n, m):
     
    # we will use a 2D vector to
    # store the diagonals of our array
    # the 2D vector will have (n+m-1)
    # rows that is equal to the number of
    # diagonals
    ans = [[] for i in range(n + m - 1)]
     
    for i in range(m):
        for j in range(n):
            ans[i + j].append(arr[j][i])
     
    for i in range(len(ans)):
        for j in range(len(ans[i])):
            print(ans[i][j], end = " ")
        print()
 
# Driver Code
# we have a matrix of n rows
# and m columns
n = 5
m = 4
 
# Function call
arr = [[1, 2, 3, 4],[ 5, 6, 7, 8],[9, 10, 11, 12 ],[13, 14, 15, 16 ],[ 17, 18, 19, 20]]
diagonalOrder(arr, n, m)
 
# This code is contributed by rag2127

C#

using System;
using System.Collections.Generic;
 
public class GFG
{
 
  public static int R = 5, C = 4;
  public static void diagonalOrder(int[,] arr, int n, int m)
  {
 
    // we will use a 2D vector to
    // store the diagonals of our array
    // the 2D vector will have (n+m-1)
    // rows that is equal to the number of
    // diagonals
    List> ans = new List>(n+m-1);
    for(int i = 0; i < n + m - 1; i++)
    {
      ans.Add(new List());
    }
 
    for (int i = 0; i < n; i++)
    {
      for (int j = 0; j < m; j++)
      {
        (ans[i + j]).Add(arr[i, j]);
      }
    }
 
    for (int i = 0; i < ans.Count; i++)
    {
      for (int j = ans[i].Count - 1; j >= 0; j--)
      {   
        Console.Write(ans[i][j] + " ");
      }  
      Console.WriteLine();
    }
 
  }
  // Driver code
  static public void Main ()
  {
    int n = 5, m = 4;
    int[,] arr={
      { 1, 2, 3, 4 },
      { 5, 6, 7, 8 },
      { 9, 10, 11, 12 },
      { 13, 14, 15, 16 },
      { 17, 18, 19, 20 },
    };
 
    // Function call
    diagonalOrder(arr, n, m);
  }
}
 
// This code is contributed by avanitrachhadiya2155
输出
1 
5 2 
9 6 3 
13 10 7 4 
17 14 11 8 
18 15 12 
19 16 
20 


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