Diagonal Traversal of a Matrix II
Given a vectors of vectors arr[], the task is to print the elements of arr[] in the diagonally upwards order as illustrated below.
Examples:
Input: arr[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
Output: 1 4 2 7 5 3 8 6 9
Explanation:
Below is the illustration of how diagonally upward order is printed:
Input: arr[][] = {{1, 2, 3, 4, 5}, {6, 7}, {8}, {9, 10, 11}, {12, 13, 14, 15, 16}}
Output: 1 6 28 7 3 9 4 12 10 5 13 11 14 15 16
Explanation:
Below is the illustration of how diagonally upward order is printed:
Approach: The idea is based on the observation that all elements in a particular upward diagonal have a sum equal to the (row index + column index). Follow the steps to solve the problem:
- Initialize a vector of vectors v to store the elements in the desired format.
- Iterate over the matrix arr[][] using variables i and j and for each i and j push arr[i][j] to v[i + j].
- After the above steps, reverse every row in the v.
- Now, print all elements in stored in v row-wise to get the desired result.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void printDiagonalTraversal(
vector<vector< int > >& 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();
}
}
vector<vector< int > > v(2 * max_size - 1);
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]);
}
}
for ( int i = 0; i < v.size(); i++) {
reverse(v[i].begin(), v[i].end());
for ( int j = 0; j < v[i].size(); j++)
cout << v[i][j] << " " ;
}
}
int main()
{
vector<vector< int > > arr
= { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
printDiagonalTraversal(arr);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void printDiagonalTraversal( int [][] nums)
{
int max_size = nums[ 0 ].length;
ArrayList<
ArrayList<Integer>> v = new ArrayList<
ArrayList<Integer>>();
for ( int i = 0 ; i < 2 * max_size - 1 ; i++)
{
v.add( new ArrayList<Integer>());
}
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]);
}
}
for ( int i = 0 ; i < v.size(); i++)
{
for ( int j = v.get(i).size() - 1 ;
j >= 0 ; j--)
{
System.out.print(v.get(i).get(j) + " " );
}
}
}
public static void main(String[] args)
{
int [][] arr = { { 1 , 2 , 3 },
{ 4 , 5 , 6 },
{ 7 , 8 , 9 } };
printDiagonalTraversal(arr);
}
}
|
Python3
def printDiagonalTraversal(nums):
max_size = len (nums)
for i in range ( len (nums)):
if (max_size < len (nums[i])):
max_size = len (nums[i])
v = [[] for i in range ( 2 * max_size - 1 )]
for i in range ( len (nums)):
for j in range ( len (nums[i])):
v[i + j].append(nums[i][j])
for i in range ( len (v)):
v[i] = v[i][:: - 1 ]
for j in range ( len (v[i])):
print (v[i][j], end = " " )
if __name__ = = '__main__' :
arr = [ [ 1 , 2 , 3 ],
[ 4 , 5 , 6 ],
[ 7 , 8 , 9 ] ]
printDiagonalTraversal(arr)
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void printDiagonalTraversal( int [,] nums)
{
int max_size = nums.GetLength(0);
List<List< int >> v = new List<List< int >>();
for ( int i = 0; i < 2 * max_size - 1; i++)
{
v.Add( new List< int >());
}
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]);
}
}
for ( int i = 0; i < v.Count; i++)
{
for ( int j = v[i].Count - 1; j >= 0; j--)
{
Console.Write(v[i][j] + " " );
}
}
}
static void Main()
{
int [,] arr = { { 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 } };
printDiagonalTraversal(arr);
}
}
|
Javascript
<script>
function printDiagonalTraversal(nums)
{
let max_size = nums[0].length;
let v = [];
for (let i = 0; i < 2 * max_size - 1; i++)
{
v.push([]);
}
for (let i = 0; i < nums[0].length; i++)
{
for (let j = 0; j < nums[0].length; j++)
{
v[i + j].push(nums[i][j]);
}
}
for (let i = 0; i < v.length; i++)
{
for (let j = v[i].length - 1;
j >= 0; j--)
{
document.write(v[i][j] + " " );
}
}
}
let arr = [ [ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ] ];
printDiagonalTraversal(arr);
</script>
|
Output:
1 4 2 7 5 3 8 6 9
Time Complexity: O(N*M), where N is the size of the given matrix and M is maximum size of any row in the matrix.
Auxiliary Space: O(N*M)
Alternate Approach: The above problem can be also be solved by using queue. Follow the steps to solve the problem:
- Initialize a queue Q, and insert the index of the first cell of arr[][], i.e., (0, 0).
- Initialize a vector v to store the elements in the desired format.
- While q is not empty, do the following:
- Pop the element at front of the queue and push it in v.
- Push the index of the current cell just below it, only if the current cell is the first in its row.
- Push the index of its right neighbor cell if it exists.
- After the above steps, print all elements stored in v.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void printDiagonalTraversal(
vector<vector< int > >& nums)
{
int m = nums.size();
queue<pair< int , int > > q;
q.push({ 0, 0 });
while (!q.empty()) {
pair< int , int > p = q.front();
q.pop();
cout << nums[p.first][p.second]
<< " " ;
if (p.second == 0
&& p.first + 1 < m) {
q.push({ p.first + 1,
p.second });
}
if (p.second + 1 < nums[p.first].size())
q.push({ p.first,
p.second + 1 });
}
}
int main()
{
vector<vector< int > > arr
= { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
printDiagonalTraversal(arr);
return 0;
}
|
Java
import java.util.*;
class GFG{
static class pair
{
int first, second;
public pair( int first, int second)
{
this .first = first;
this .second = second;
}
}
static void printDiagonalTraversal(
int [][]nums)
{
int m = nums.length;
Queue<pair> q = new LinkedList<>();
q.add( new pair( 0 , 0 ));
while (!q.isEmpty()) {
pair p = q.peek();
q.remove();
System.out.print(nums[p.first][p.second]
+ " " );
if (p.second == 0
&& p.first + 1 < m) {
q.add( new pair( p.first + 1 ,
p.second ));
}
if (p.second + 1 < nums[p.first].length)
q.add( new pair( p.first,
p.second + 1 ));
}
}
public static void main(String[] args)
{
int [][] arr
= { { 1 , 2 , 3 }, { 4 , 5 , 6 }, { 7 , 8 , 9 } };
printDiagonalTraversal(arr);
}
}
|
Python3
def printDiagonalTraversal(nums):
m = len (nums)
q = []
q.append([ 0 , 0 ])
while ( len (q) ! = 0 ):
p = q[ 0 ]
q.pop( 0 );
print (nums[p[ 0 ]][p[ 1 ]], end = " " )
if (p[ 1 ] = = 0
and p[ 0 ] + 1 < m):
q.append([ p[ 0 ] + 1 ,
p[ 1 ] ]);
if (p[ 1 ] + 1 < len (nums[p[ 0 ]])):
q.append([ p[ 0 ],
p[ 1 ] + 1 ]);
if __name__ = = "__main__" :
arr = [[ 1 , 2 , 3 ], [ 4 , 5 , 6 ] ,[ 7 , 8 , 9 ]]
printDiagonalTraversal(arr);
|
C#
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;
}
}
static void printDiagonalTraversal(
int [,]nums)
{
int m = nums.GetLength(0);
Queue<pair> q = new Queue<pair>();
q.Enqueue( new pair(0, 0));
while (q.Count != 0)
{
pair p = q.Peek();
q.Dequeue();
Console.Write(nums[p.first,p.second]
+ " " );
if (p.second == 0
&& p.first + 1 < m)
{
q.Enqueue( new pair( p.first + 1,
p.second ));
}
if (p.second + 1 < nums.GetLength(1))
q.Enqueue( new pair( p.first,
p.second + 1 ));
}
}
public static void Main(String[] args)
{
int [,] arr
= { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
printDiagonalTraversal(arr);
}
}
|
Javascript
<script>
class pair
{
constructor(first,second)
{
this .first = first;
this .second = second;
}
}
function printDiagonalTraversal(nums)
{
let m = nums.length;
let q = [];
q.push( new pair( 0, 0 ));
while (q.length!=0) {
let p = q[0];
q.shift();
document.write(nums[p.first][p.second]
+ " " );
if (p.second == 0
&& p.first + 1 < m) {
q.push( new pair( p.first + 1,
p.second ));
}
if (p.second + 1 < nums[p.first].length)
q.push( new pair( p.first,
p.second + 1 ));
}
}
let arr=[[ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9] ];
printDiagonalTraversal(arr);
</script>
|
Output:
1 4 2 7 5 3 8 6 9
Time Complexity: O(N*M), where N is the size of the given matrix and M is maximum size of any row in the matrix.
Auxiliary Space: O(N)
Last Updated :
15 Mar, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...