原文:

给定向量 arr[]

示例:

输入: arr[][] = {{1,2,3},{4,5,6},{7,8,9}} 输出: 1 4 2 7 5 3 8 6 9 解释: 以下是如何按对角线向上的顺序打印的图示:

输入: arr[][] = {{1,2,3,4,5},{6,7},{8},{9,10,11},{12,13,14,15,16}} 输出:1 6 28 7 3 9 4 12 10 5 13 11 14 15 16 解释: 下图是如何按对角线向上的顺序打印:

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

  • 初始化向量的向量 v ,以所需的格式存储元素。
  • arr【】【】【】t3】,对于每个 ijarr【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

python 3

# 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

java 描述语言


output: 

1 4 2 7 5 3 8 6 9

时间复杂度: o(nm),其中 n 是给定矩阵的大小,m 是矩阵中任意一行的最大大小。* 辅助空间: o(nm)*

交替进场:使用也可以解决上述问题。按照以下步骤解决问题:

  • 初始化一个队列 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

python 3

# 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

java 描述语言


output: 

1 4 2 7 5 3 8 6 9

时间复杂度: o(nm),其中 n 是给定矩阵的大小,m 是矩阵中任意一行的最大大小。* 辅助空间: o(n)