Maximum difference of indices (i, j) such that A[i][j] = 0 in the given matrix in C++


We are given with a matrix of size n x n and a condition that a[i][j] = 0 and the task is to calculate the maximum difference of indices having a[i][j] = 0. So, we can clearly state that there must be at least one zero in a matrix.

Input 

int matrix[][] = {
   {0, 1, 1},
   {0, 0, 0},
   {4, 5, 1}}

Output −Maximum difference of indices (i, j) such that A[i][j] = 0 in the given matrix is −

Explanation − we have element 0 at matrix[0][0], matrix[1][0], matrix[1][1] and matrix[1][2]. So the maximum difference of indices will be at matrix[1][0] which is having element 0. So the maximum difference is 1.

Input 

int matrix[][] = {
   {0, 1, 1},
   {0, 2, 9},
   {4, 0, 1}}

Output − Maximum difference of indices (i, j) such that A[i][j] = 0 in the given matrix is −

Explanation − we have element 0 at matrix[0][0], matrix[1][0] and matrix[2][1]. So the maximum difference of indices will be at matrix[1][0] and matrix[2][1] which is having element 0. So the maximum difference is 1.

Approach used in the below program is as follows

  • Input the matrix such that it should contain at least one 1 at any indices.

  • Define the row and column maximum size i.e. size of n x n.

  • Take a temporary variable that will store the maximum difference value.

  • Start loop For from 0 till row_size

  • Inside the loop, start another loop For from 0 till col_size

  • Check IF matrix[i][j] = 0

  • Then set max value to be the max value as difference between the indices.

  • Return the max value

  • Print the result.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
#define row 3
#define col 3
//find maximum difference
int maximum(int matrix[row][col]){
   int max_val = 0;
   for (int i = 0; i < row; i++){
      for (int j = 0; j < col; j++){
         if (matrix[i][j] == 0){
            max_val = max(max_val, abs(i - j));
         }
      }
   }
   return max_val;
}
int main(){
   int matrix[row][col] = {
      { 1, 2, 0},
      { 0, 4, 0},
      { 0, 1, 0}};
   cout<<"Maximum difference of indices with A[i][j] = 0 is: "<<maximum(matrix);
   return 0;
}

Output

If we run the above code we will get the following output −

Maximum difference of indices with A[i][j] = 0 is: 2

Updated on: 14-Aug-2020

69 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements