Question: import java.util. * ; class DiagonalSumDebug { public static void main ( String args [ ] ) { Scanner sc = new Scanner ( System

import java.util.*;
class DiagonalSumDebug {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int x = sc.nextInt();
int y = sc.nextInt();
int a[][]= new int[100001][100001];
for (int i =0; i < n; i++){
for (int j =0; j < m; j++)
a[i][j]= sc.nextInt();
}
int result = diagonalSum(a,x,y,n,m);
System.out.println(result);
}
static int diagonalSum(int[][] a,int n,int m,int i,int j){
if (i >= n || j >= m){
return -1;
}
int diagonalSum;
int row = i;
int col = j;
while (row < n)
{
diagonalSum += a[row][col];
row++;
col++;
}
return diagonalSum;
}
} Problem Description
Given a matrix of dimensions n x m, you are tasked with finding the sum of elements by starting at the index (i, j) and moving in a diagonal order.
Write a function that takes the matrix, starting index (i, j), and returns the sum of the elements encountered while moving diagonally. If the starting index is invalid, return -1
Input format
First line contains integers n and m.
Second line contains starting index i and j.
In next n lines each line contains m elements.
Output format
An integer representing the sum.
Sample Input 1
44
01
1234
1245
2334
1123
Sample Output 1
10
Explanation
Diagonal elements starting at index (0,2) are 2,4,4.
Their sum is 10.
Constraints
1<= n,m <=100
0<= i,j <100
0<= element of matrix <=10^5

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!