Matrix Reverse Diagonal Consistency
· unclassifiedUnclassifiedarraysmatrix
Problem
You are given a matrix of size M × N.
Each group of elements that lie on the same diagonal from top-right to bottom-left is considered a diagonal group.
These diagonals are formed using:
i − j = constant
Check whether all elements in every diagonal group are equal.
- If YES → return sum of first row
- If NO → return product of first row
Example
Input
3 3 6 4 2 7 2 1 2 5 3
Output
48
Use a HashMap where key = (i − j) and value = first element of that diagonal.
Compare remaining elements in same diagonal.
```java
import java.util.*;
class Main{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int m=sc.nextInt();
int n=sc.nextInt();
int[][] mat=new int[m][n];
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
mat[i][j]=sc.nextInt();
}
}
boolean flag=true;
HashMap<Integer,Integer> map=new HashMap<>();
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
int key=i-j;
if(!map.containsKey(key)){
map.put(key,mat[i][j]);
}else{
if(map.get(key)!=mat[i][j]){
flag=false;
}
}
}
}
int result=1;
if(flag){
result=0;
for(int j=0;j<n;j++){
result+=mat[0][j];
}
}else{
for(int j=0;j<n;j++){
result*=mat[0][j];
}
}
System.out.println(result);
}
}
```
Diagonal [6,2,5] is not equal → condition fails
First row = [6,4,2] → product = 48
java
import java.util.*;
class Main{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int m=sc.nextInt();
int n=sc.nextInt();
int[][] mat=new int[m][n];
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
mat[i][j]=sc.nextInt();
}
}
boolean flag=true;
HashMap<Integer,Integer> map=new HashMap<>();
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
int key=i-j;
if(!map.containsKey(key)){
map.put(key,mat[i][j]);
}else{
if(map.get(key)!=mat[i][j]){
flag=false;
}
}
}
}
int result=1;
if(flag){
result=0;
for(int j=0;j<n;j++){
result+=mat[0][j];
}
}else{
for(int j=0;j<n;j++){
result*=mat[0][j];
}
}
System.out.println(result);
}
}