Problem: Write a Program in C to find an element that is the minimum in the row but maximum in the column in the given matrix.

Example:

Matrix:
1 2 3
4 5 6
7 8 9

Here, 7 is the smallest element in the row but the largest in its column.

To solve this problem, we have to check each element in the given matrix, whether it is the minimum element in its row and the maximum in its column.

For this, we select each element individually from the matrix compare it with all the elements of the same row and column.

Here is the implementation of the idea in C:

#include <stdio.h>
#include <stdlib.h>
 
int main()
{
  int n;

  //Input the order of the square matrix
  printf("Enter the size of Matrix NxN: \n");
  scanf("%d",&n);

  //create a square Matrix
  int arr[n][n];

  //Input elements in the matrix
  printf("Enter %d Numbers into matrix: \n",n*n);
  for(int i=0; i<n; i++){
    for(int j=0; j<n; j++){
      scanf("%d", &arr[i][j]);
    }
  }

  //declare max and min variable
  int max_in_col, min_in_row;

  //Iterate through each row and column index
  for(int i=0; i<n; i++){
    for(int j=0; j<n; j++){
      min_in_row = max_in_col =arr[i][j];
      
      //Find the min of the current row
      for(int k=0; k<n; k++){
        if (arr[i][k] < min_in_row ){
          min_in_row = arr[i][k];
        }
      }

      //Find the max of the current column
      for(int k=0; k<n; k++){
        if (arr[k][j] > max_in_col ){
          max_in_col = arr[k][j];
        }
      }

      /*
        *If min and max are both same then that
        *number is the result which we are looking for
      */
      if(min_in_row == arr[i][j] && max_in_col == arr[i][j]){
        printf("Found an element: %d \n", min_in_row);
      }
    }
  }

  return 0;
}

Output:

Enter the size of Matrix NxN:
3
Enter 9 Numbers into matrix:
1 2 3
4 5 6
7 8 9

Found an element: 7


In this tutorial, we learned to find the elements in a matrix which is minimum in the row but maximum in the column.

Leave a Reply