Finding the converging element of the diagonals in a square matrix
Given a square matrix, the task is to find the element of the matrix where the right and the left diagonal of this square matrix converge.
Example:
Input: n = 5, matrix =
[ 1 2 3 4 5
5 6 7 8 6
9 5 6 8 7
2 3 5 6 8
1 2 3 4 5 ]
Output: 6
Input: n = 4, matrix =
[ 1 2 3 4
5 6 7 8
9 0 1 2
4 5 6 1 ]
Output: NULL
Here there no converging element at all.
Hence the answer is null.
Approach:
- If the number of rows and column of the matrix are even, then we just print NULL because there would be no converging element in the case of even number of rows and column.
- If the number of rows and column of the matrix are odd, find the mid-value of n as
mid = n/2
- The arr[mid][mid] itself is the converging diagonal element.
Below is the implementation of the above approach:
C++
#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n = 5;
int a[][5] = { { 1, 2, 3, 4, 5 },
{ 5, 6, 7, 8, 6 },
{ 9, 5, 6, 8, 7 },
{ 2, 3, 5, 6, 8 },
{ 1, 2, 3, 4, 5 } };
int convergingele, mid;
int i, j;
if (n % 2 == 0) {
printf ( "NULL\n" );
}
else {
mid = n / 2;
convergingele = a[mid][mid];
printf ( "%d\n" , convergingele);
}
}
|
Java
class GFG
{
public static void main(String args[])
{
int n = 5 ;
int a[][] = {{ 1 , 2 , 3 , 4 , 5 },
{ 5 , 6 , 7 , 8 , 6 },
{ 9 , 5 , 6 , 8 , 7 },
{ 2 , 3 , 5 , 6 , 8 },
{ 1 , 2 , 3 , 4 , 5 }};
int convergingele, mid;
int i, j;
if (n % 2 == 0 )
{
System.out.printf( "NULL\n" );
}
else
{
mid = n / 2 ;
convergingele = a[mid][mid];
System.out.printf( "%d\n" , convergingele);
}
}
}
|
Python3
n = 5
a = [[ 1 , 2 , 3 , 4 , 5 ],
[ 5 , 6 , 7 , 8 , 6 ],
[ 9 , 5 , 6 , 8 , 7 ],
[ 2 , 3 , 5 , 6 , 8 ],
[ 1 , 2 , 3 , 4 , 5 ]]
if (n % 2 = = 0 ):
print ( "NULL" )
else :
mid = n / / 2
convergingele = a[mid][mid]
print (convergingele)
|
C#
using System;
class GFG
{
public static void Main(String []args)
{
int n = 5;
int [,]a = {{1, 2, 3, 4, 5},
{5, 6, 7, 8, 6},
{9, 5, 6, 8, 7},
{2, 3, 5, 6, 8},
{1, 2, 3, 4, 5}};
int convergingele, mid;
if (n % 2 == 0)
{
Console.Write( "NULL\n" );
}
else
{
mid = n / 2;
convergingele = a[mid,mid];
Console.Write( "{0}\n" , convergingele);
}
}
}
|
Javascript
<script>
let n = 5;
let a = [ [ 1, 2, 3, 4, 5 ],
[ 5, 6, 7, 8, 6 ],
[ 9, 5, 6, 8, 7 ],
[ 2, 3, 5, 6, 8 ],
[ 1, 2, 3, 4, 5 ] ];
let convergingele, mid;
let i, j;
if (n % 2 == 0) {
document.write( "NULL<br>" );
}
else
{
mid = parseInt(n / 2);
convergingele = a[mid][mid];
document.write(convergingele + "<br>" );
}
</script>
|
Time complexity: O(1) because performing constant operations
Auxiliary space: O(1)
Last Updated :
10 Aug, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...