📜  以对角向上的方式从左上到右下打印矩阵元素

📅  最后修改于: 2021-05-07 07:38:03             🧑  作者: Mango

给定向量arr []的向量,任务是按照对角线向上的顺序打印arr []的元素,如下所示。

例子:

方法:该思想基于以下观察:特定向上对角线中的所有元素的总和等于(行索引+列索引) 。请按照以下步骤解决问题:

  • 初始化向量v的向量,以所需格式存储元素。
  • 使用变量ij遍历矩阵arr [] [] ,对于每个ij,arr [i] [j]推到v [i + j]
  • 完成上述步骤后,反转v中的每一行。
  • 现在,按行打印存储在v中的所有元素,以获得所需的结果。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to traverse the matrix
// diagonally upwards
void printDiagonalTraversal(
    vector >& nums)
{
    // Stores the maximum size of vector
    // from all row of matrix nums[][]
    int max_size = nums.size();
 
    for (int i = 0; i < nums.size(); i++) {
        if (max_size < nums[i].size()) {
            max_size = nums[i].size();
        }
    }
 
    // Store elements in desired order
    vector > v(2 * max_size - 1);
 
    // Store every element on the basis
    // of sum of index (i + j)
    for (int i = 0; i < nums.size(); i++) {
 
        for (int j = 0;
             j < nums[i].size(); j++) {
            v[i + j].push_back(nums[i][j]);
        }
    }
 
    // Print the stored result
    for (int i = 0; i < v.size(); i++) {
 
        // Reverse all sublist
        reverse(v[i].begin(), v[i].end());
 
        for (int j = 0; j < v[i].size(); j++)
            cout << v[i][j] << " ";
    }
}
 
// Driver code
int main()
{
    // Given vector of vectors arr
    vector > arr
        = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
 
    // Function Call
    printDiagonalTraversal(arr);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
     
// Function to traverse the matrix
// diagonally upwards
static void printDiagonalTraversal(int[][] nums)
{
     
    // Stores the maximum size of vector
    // from all row of matrix nums[][]
    int max_size = nums[0].length;
   
    // Store elements in desired order
    ArrayList<
    ArrayList> v = new ArrayList<
                                ArrayList>();
                                 
    for(int i = 0; i < 2 * max_size - 1; i++)
    {
        v.add(new ArrayList());
    }
   
    // Store every element on the basis
    // of sum of index (i + j)
    for(int i = 0; i < nums[0].length; i++)
    {
        for(int j = 0; j < nums[0].length; j++)
        {
            v.get(i + j).add(nums[i][j]);
        }
    }
   
    // Print the stored result
    for(int i = 0; i < v.size(); i++)
    {
          
        // Print in reverse order
        for(int j = v.get(i).size() - 1;
                j >= 0; j--)
        {
            System.out.print(v.get(i).get(j) + " ");
        }
    }
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given vector of vectors arr
    int[][] arr = { { 1, 2, 3 },
                    { 4, 5, 6 },
                    { 7, 8, 9 } };
      
    // Function Call
    printDiagonalTraversal(arr);
}
}
 
// This code is contributed by divyeshrabadiya07


Python3
# Python3 program for the above approach
 
# Function to traverse the matrix
# diagonally upwards
def printDiagonalTraversal(nums):
     
    # Stores the maximum size of vector
    # from all row of matrix nums[][]
    max_size = len(nums)
 
    for i in range(len(nums)):
        if (max_size < len(nums[i])):
            max_size = len(nums[i])
 
    # Store elements in desired order
    v = [[] for i in range(2 * max_size - 1)]
 
    # Store every element on the basis
    # of sum of index (i + j)
    for i in range(len(nums)):
        for j in range(len(nums[i])):
            v[i + j].append(nums[i][j])
 
    # Print the stored result
    for i in range(len(v)):
 
        # Reverse all sublist
        v[i] = v[i][::-1]
 
        for j in range(len(v[i])):
            print(v[i][j], end = " ")
 
# Driver code
if __name__ == '__main__':
     
    # Given vector of vectors arr
    arr = [ [ 1, 2, 3 ],
            [ 4, 5, 6 ],
            [ 7, 8, 9 ] ]
 
    # Function Call
    printDiagonalTraversal(arr)
 
# This code is contributed by mohit kumar 29


C#
// C# program for the above approach
using System;
using System.Collections.Generic; 
 
class GFG{
     
// Function to traverse the matrix
// diagonally upwards
static void printDiagonalTraversal(int[,] nums)
{
     
    // Stores the maximum size of vector
    // from all row of matrix nums[][]
    int max_size = nums.GetLength(0);
  
    // Store elements in desired order
    List> v = new List>();
    for(int i = 0; i < 2 * max_size - 1; i++)
    {
        v.Add(new List());
    }
  
    // Store every element on the basis
    // of sum of index (i + j)
    for(int i = 0; i < nums.GetLength(0); i++)
    {
        for(int j = 0; j < nums.GetLength(0); j++)
        {
            v[i + j].Add(nums[i, j]);
        }
    }
  
    // Print the stored result
    for(int i = 0; i < v.Count; i++)
    {
         
        // print in reverse order
        for(int j = v[i].Count - 1; j >= 0; j--)
        {
            Console.Write(v[i][j] + " ");
        }
    }
}
 
// Driver Code
static void Main()
{
     
    // Given vector of vectors arr
    int[,] arr = { { 1, 2, 3 },
                   { 4, 5, 6 },
                   { 7, 8, 9 } };
     
    // Function Call
    printDiagonalTraversal(arr);
}
}
 
// This code is contributed by divyesh072019


C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to traverse the matrix
// diagonally upwards
void printDiagonalTraversal(
    vector >& nums)
{
    // Store the number of rows
    int m = nums.size();
 
    // Initialize queue
    queue > q;
 
    // Push the index of first element
    // i.e., (0, 0)
    q.push({ 0, 0 });
 
    while (!q.empty()) {
 
        // Get the front element
        pair p = q.front();
 
        // Pop the element at the front
        q.pop();
        cout << nums[p.first][p.second]
             << " ";
 
        // Insert the element below
        // if the current element is
        // in first column
        if (p.second == 0
            && p.first + 1 < m) {
            q.push({ p.first + 1,
                     p.second });
        }
 
        // Insert the right neighbour
        // if it exists
        if (p.second + 1 < nums[p.first].size())
            q.push({ p.first,
                     p.second + 1 });
    }
}
 
// Driver Code
int main()
{
    // Given vector of vectors arr
    vector > arr
        = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
 
    // Function call
    printDiagonalTraversal(arr);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
     
    static class pair
    {
        int first, second;
        public pair(int first, int second) 
        {
            this.first = first;
            this.second = second;
        }   
    }
   
// Function to traverse the matrix
// diagonally upwards
static void printDiagonalTraversal(
    int [][]nums)
{
   
    // Store the number of rows
    int m = nums.length;
 
    // Initialize queue
    Queue q = new LinkedList<>();
 
    // Push the index of first element
    // i.e., (0, 0)
    q.add(new pair( 0, 0 ));
 
    while (!q.isEmpty()) {
 
        // Get the front element
        pair p = q.peek();
 
        // Pop the element at the front
        q.remove();
        System.out.print(nums[p.first][p.second]
            + " ");
 
        // Insert the element below
        // if the current element is
        // in first column
        if (p.second == 0
            && p.first + 1 < m) {
            q.add(new pair( p.first + 1,
                     p.second ));
        }
 
        // Insert the right neighbour
        // if it exists
        if (p.second + 1 < nums[p.first].length)
            q.add(new pair(  p.first,
                     p.second + 1 ));
    }
}
 
// Driver Code
public static void main(String[] args)
{
    // Given vector of vectors arr
    int[][] arr
        = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
 
    // Function call
    printDiagonalTraversal(arr);
 
}
}
 
// This code is contributed by Amit Katiyar


Python3
# Python3 program for the above approach
 
# Function to traverse the matrix
# diagonally upwards
def printDiagonalTraversal(nums):
 
    # Store the number of rows
    m = len(nums)
 
    # Initialize queue
    q = []
 
    # Push the index of first element
    # i.e., (0, 0)
    q.append([ 0, 0 ])
 
    while (len(q) != 0):
 
        # Get the front element
        p = q[0]
 
        # Pop the element at the front
        q.pop(0);
        print(nums[p[0]][p[1]], end = " ")
 
        # Insert the element below
        # if the current element is
        # in first column
        if (p[1] == 0
            and p[0] + 1 < m):
            q.append([ p[0]+ 1,
                     p[1] ]);
         
        # Insert the right neighbour
        # if it exists
        if (p[1] + 1 < len(nums[p[0]])):
            q.append([ p[0],
                     p[1] + 1 ]);
 
# Driver Code
if __name__ == "__main__":
   
    # Given vector of vectors arr
    arr = [[ 1, 2, 3 ], [ 4, 5, 6 ] ,[ 7, 8, 9 ]]
 
    # Function call
    printDiagonalTraversal(arr);
 
    # This code is contributed by chitranayal


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
public class GFG
{
    class pair
    {
        public int first, second;
        public pair(int first, int second) 
        {
            this.first = first;
            this.second = second;
        }   
    }
   
// Function to traverse the matrix
// diagonally upwards
static void printDiagonalTraversal(
    int [,]nums)
{
   
    // Store the number of rows
    int m = nums.GetLength(0);
 
    // Initialize queue
    Queue q = new Queue();
 
    // Push the index of first element
    // i.e., (0, 0)
    q.Enqueue(new pair(0, 0));
    while (q.Count != 0)
    {
 
        // Get the front element
        pair p = q.Peek();
 
        // Pop the element at the front
        q.Dequeue();
        Console.Write(nums[p.first,p.second]
            + " ");
 
        // Insert the element below
        // if the current element is
        // in first column
        if (p.second == 0
            && p.first + 1 < m)
        {
            q.Enqueue(new pair( p.first + 1,
                     p.second ));
        }
 
        // Insert the right neighbour
        // if it exists
        if (p.second + 1 < nums.GetLength(1))
            q.Enqueue(new pair(  p.first,
                     p.second + 1 ));
    }
}
 
// Driver Code
public static void Main(String[] args)
{
   
    // Given vector of vectors arr
    int[,] arr
        = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
 
    // Function call
    printDiagonalTraversal(arr);
}
}
 
// This code is contributed by shikhasingrajput


输出:
1 4 2 7 5 3 8 6 9

时间复杂度: O(N * M),其中N是给定矩阵的大小,M是矩阵中任何行的最大大小。
辅助空间: O(N * M)

替代方法:上述问题也可以通过使用队列来解决。请按照以下步骤解决问题:

  • 初始化队列Q ,并插入arr [] []的第一个单元格的索引,即(0,0)
  • 初始化向量v以所需的格式存储元素。
  • 当q不为空时,请执行以下操作:
    • 弹出队列前面的元素,然后将其推入v 
    • 仅当当前单元格在其行中的第一个位置时,才将当前单元格的索引推入它的正下方。
    • 如果存在,则推入其右相邻单元格的索引。
  • 完成上述步骤后,打印存储在v中的所有元素。

下面是上述方法的实现:

C++

// C++ program for the above approach
#include 
using namespace std;
 
// Function to traverse the matrix
// diagonally upwards
void printDiagonalTraversal(
    vector >& nums)
{
    // Store the number of rows
    int m = nums.size();
 
    // Initialize queue
    queue > q;
 
    // Push the index of first element
    // i.e., (0, 0)
    q.push({ 0, 0 });
 
    while (!q.empty()) {
 
        // Get the front element
        pair p = q.front();
 
        // Pop the element at the front
        q.pop();
        cout << nums[p.first][p.second]
             << " ";
 
        // Insert the element below
        // if the current element is
        // in first column
        if (p.second == 0
            && p.first + 1 < m) {
            q.push({ p.first + 1,
                     p.second });
        }
 
        // Insert the right neighbour
        // if it exists
        if (p.second + 1 < nums[p.first].size())
            q.push({ p.first,
                     p.second + 1 });
    }
}
 
// Driver Code
int main()
{
    // Given vector of vectors arr
    vector > arr
        = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
 
    // Function call
    printDiagonalTraversal(arr);
 
    return 0;
}

Java

// Java program for the above approach
import java.util.*;
 
class GFG{
     
    static class pair
    {
        int first, second;
        public pair(int first, int second) 
        {
            this.first = first;
            this.second = second;
        }   
    }
   
// Function to traverse the matrix
// diagonally upwards
static void printDiagonalTraversal(
    int [][]nums)
{
   
    // Store the number of rows
    int m = nums.length;
 
    // Initialize queue
    Queue q = new LinkedList<>();
 
    // Push the index of first element
    // i.e., (0, 0)
    q.add(new pair( 0, 0 ));
 
    while (!q.isEmpty()) {
 
        // Get the front element
        pair p = q.peek();
 
        // Pop the element at the front
        q.remove();
        System.out.print(nums[p.first][p.second]
            + " ");
 
        // Insert the element below
        // if the current element is
        // in first column
        if (p.second == 0
            && p.first + 1 < m) {
            q.add(new pair( p.first + 1,
                     p.second ));
        }
 
        // Insert the right neighbour
        // if it exists
        if (p.second + 1 < nums[p.first].length)
            q.add(new pair(  p.first,
                     p.second + 1 ));
    }
}
 
// Driver Code
public static void main(String[] args)
{
    // Given vector of vectors arr
    int[][] arr
        = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
 
    // Function call
    printDiagonalTraversal(arr);
 
}
}
 
// This code is contributed by Amit Katiyar

Python3

# Python3 program for the above approach
 
# Function to traverse the matrix
# diagonally upwards
def printDiagonalTraversal(nums):
 
    # Store the number of rows
    m = len(nums)
 
    # Initialize queue
    q = []
 
    # Push the index of first element
    # i.e., (0, 0)
    q.append([ 0, 0 ])
 
    while (len(q) != 0):
 
        # Get the front element
        p = q[0]
 
        # Pop the element at the front
        q.pop(0);
        print(nums[p[0]][p[1]], end = " ")
 
        # Insert the element below
        # if the current element is
        # in first column
        if (p[1] == 0
            and p[0] + 1 < m):
            q.append([ p[0]+ 1,
                     p[1] ]);
         
        # Insert the right neighbour
        # if it exists
        if (p[1] + 1 < len(nums[p[0]])):
            q.append([ p[0],
                     p[1] + 1 ]);
 
# Driver Code
if __name__ == "__main__":
   
    # Given vector of vectors arr
    arr = [[ 1, 2, 3 ], [ 4, 5, 6 ] ,[ 7, 8, 9 ]]
 
    # Function call
    printDiagonalTraversal(arr);
 
    # This code is contributed by chitranayal

C#

// C# program for the above approach
using System;
using System.Collections.Generic;
public class GFG
{
    class pair
    {
        public int first, second;
        public pair(int first, int second) 
        {
            this.first = first;
            this.second = second;
        }   
    }
   
// Function to traverse the matrix
// diagonally upwards
static void printDiagonalTraversal(
    int [,]nums)
{
   
    // Store the number of rows
    int m = nums.GetLength(0);
 
    // Initialize queue
    Queue q = new Queue();
 
    // Push the index of first element
    // i.e., (0, 0)
    q.Enqueue(new pair(0, 0));
    while (q.Count != 0)
    {
 
        // Get the front element
        pair p = q.Peek();
 
        // Pop the element at the front
        q.Dequeue();
        Console.Write(nums[p.first,p.second]
            + " ");
 
        // Insert the element below
        // if the current element is
        // in first column
        if (p.second == 0
            && p.first + 1 < m)
        {
            q.Enqueue(new pair( p.first + 1,
                     p.second ));
        }
 
        // Insert the right neighbour
        // if it exists
        if (p.second + 1 < nums.GetLength(1))
            q.Enqueue(new pair(  p.first,
                     p.second + 1 ));
    }
}
 
// Driver Code
public static void Main(String[] args)
{
   
    // Given vector of vectors arr
    int[,] arr
        = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
 
    // Function call
    printDiagonalTraversal(arr);
}
}
 
// This code is contributed by shikhasingrajput
输出:
1 4 2 7 5 3 8 6 9

时间复杂度: O(N * M),其中N是给定矩阵的大小,M是矩阵中任何行的最大大小。
辅助空间: O(N)