Print the matrix diagonally downwards
Given a matrix of size n*n, print the matrix in the following pattern.
Output: 1 2 5 3 6 9 4 7 10 13 8 11 14 12 15 16
Examples:
Input :matrix[2][2]= { {1, 2},
{3, 4} }
Output : 1 2 3 4
Input :matrix[3][3]= { {1, 2, 3},
{4, 5, 6},
{7, 8, 9} }
Output : 1 2 4 3 5 7 6 8 9
Implementation: Following is the C++ implementation for the above pattern.
C++
#include <bits/stdc++.h>
using namespace std;
void printMatrixDiagonallyDown(vector<vector< int > > matrix,
int n)
{
for ( int k = 0; k < n; k++) {
int row = 0, col = k;
while (col >= 0) {
cout << matrix[row][col] << " " ;
row++, col--;
}
}
for ( int j = 1; j < n; j++) {
int col = n - 1, row = j;
while (row < n) {
cout << matrix[row][col] << " " ;
row++, col--;
}
}
}
int main()
{
vector<vector< int > > matrix{ { 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 } };
int n = 3;
printMatrixDiagonallyDown(matrix, n);
return 0;
}
|
Java
class GFG{
static void printMatrixDiagonallyDown( int [][] matrix,
int n)
{
for ( int k = 0 ; k < n; k++)
{
int row = 0 , col = k;
while (col >= 0 )
{
System.out.print(matrix[row][col] + " " );
row++;
col--;
}
}
for ( int j = 1 ; j < n; j++)
{
int col = n - 1 , row = j;
while (row < n)
{
System.out.print(matrix[row][col] + " " );
row++;
col--;
}
}
}
public static void main(String[] args)
{
int [][] matrix = {{ 1 , 2 , 3 },
{ 4 , 5 , 6 },
{ 7 , 8 , 9 }};
int n = 3 ;
printMatrixDiagonallyDown(matrix, n);
}
}
|
Python 3
def printMatrixDiagonallyDown(matrix,n):
for k in range (n):
row = 0
col = k
while (col > = 0 ):
print (matrix[row][col],end = " " )
row + = 1
col - = 1
for j in range ( 1 ,n):
col = n - 1
row = j
while (row < n):
print (matrix[row][col],end = " " )
row + = 1
col - = 1
if __name__ = = '__main__' :
matrix = [[ 1 , 2 , 3 ],[ 4 , 5 , 6 ],[ 7 , 8 , 9 ]]
n = 3
printMatrixDiagonallyDown(matrix, n)
|
C#
using System;
class GFG{
static void printMatrixDiagonallyDown( int [,] matrix,
int n)
{
for ( int k = 0; k < n; k++)
{
int row = 0, col = k;
while (col >= 0)
{
Console.Write(matrix[row,col] + " " );
row++;
col--;
}
}
for ( int j = 1; j < n; j++)
{
int col = n - 1, row = j;
while (row < n)
{
Console.Write(matrix[row,col] + " " );
row++;
col--;
}
}
}
public static void Main(String[] args)
{
int [,] matrix = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
int n = 3;
printMatrixDiagonallyDown(matrix, n);
}
}
|
Javascript
<script>
function printMatrixDiagonallyDown(matrix,n)
{
for (let k = 0; k < n; k++)
{
let row = 0, col = k;
while (col >= 0)
{
document.write(matrix[row][col] + " " );
row++;
col--;
}
}
for (let j = 1; j < n; j++)
{
let col = n - 1, row = j;
while (row < n)
{
document.write(matrix[row][col] + " " );
row++;
col--;
}
}
}
let matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]];
let n = 3;
printMatrixDiagonallyDown(matrix, n);
</script>
|
Complexity Analysis:
- Time Complexity: O(n2)
- Auxiliary Space: 1
Last Updated :
07 Sep, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...