Row-wise common elements in two diagonals of a square matrix
Last Updated :
19 Jul, 2022
Given a square matrix, find out count of numbers that are same in same row and same in both primary and secondary diagonals.
Examples :
Input : 1 2 1
4 5 2
0 5 1
Output : 2
Primary diagonal is 1 5 1
Secondary diagonal is 1 5 0
Two elements (1 and 5) match
in two diagonals and same.
Input : 1 0 0
0 1 0
0 0 1
Output : 1
Primary diagonal is 1 1 1
Secondary diagonal is 0 1 0
Only one element is same.
We can achieve this in O(n) time, O(1) space and only one traversal. We can find current element in i-th row of primary diagonal as mat[i][i] and i-th element of secondary diagonal as mat[i][n-i-1].
Implementation:
C++
#include <iostream>
#define MAX 100
using namespace std;
int countCommon( int mat[][MAX], int n)
{
int res = 0;
for ( int i=0;i<n;i++)
if (mat[i][i] == mat[i][n-i-1])
res++;
return res;
}
int main()
{
int mat[][MAX] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
cout << countCommon(mat, 3);
return 0;
}
|
Java
import java.io.*;
class GFG
{
int MAX = 100 ;
static int countCommon( int mat[][], int n)
{
int res = 0 ;
for ( int i = 0 ; i < n; i++)
if (mat[i][i] == mat[i][n - i - 1 ])
res++;
return res;
}
public static void main(String args[]) throws IOException
{
int mat[][] = {{ 1 , 2 , 3 },
{ 4 , 5 , 6 },
{ 7 , 8 , 9 }};
System.out.println(countCommon(mat, 3 ));
}
}
|
Python3
Max = 100
def countCommon(mat, n):
res = 0
for i in range (n):
if mat[i][i] = = mat[i][n - i - 1 ] :
res = res + 1
return res
mat = [[ 1 , 2 , 3 ],
[ 4 , 5 , 6 ],
[ 7 , 8 , 9 ]]
print (countCommon(mat, 3 ))
|
C#
using System;
class GFG {
static int countCommon( int [,]mat, int n)
{
int res = 0;
for ( int i = 0; i < n; i++)
if (mat[i,i] == mat[i,n - i - 1])
res++;
return res;
}
public static void Main()
{
int [,]mat = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
Console.WriteLine(countCommon(mat, 3));
}
}
|
PHP
<?php
$MAX = 100;
function countCommon( $mat , $n )
{
global $MAX ;
$res = 0;
for ( $i = 0; $i < $n ; $i ++)
if ( $mat [ $i ][ $i ] == $mat [ $i ][ $n - $i - 1])
$res ++;
return $res ;
}
$mat = array ( array (1, 2, 3),
array (4, 5, 6),
array (7, 8, 9));
echo countCommon( $mat , 3);
?>
|
Javascript
<script>
let MAX = 100;
function countCommon(mat, n)
{
let res = 0;
for (let i = 0; i < n; i++)
if (mat[i][i] == mat[i][n - i - 1])
res++;
return res;
}
let mat = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]];
document.write(countCommon(mat, 3));
</script>
|
Time Complexity: O(n).
Auxiliary Space: O(1).
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...