125. JAVA Program to Find the Saddle point of the given matrix.
How does this program work?
- In this program we are going to learn about how to find the Saddle point of the matrix using java.
- Saddle point means minimum element in row is equal to the maximum element in column of a matrix.
- Find the minimum element in its row and maximum element in its column.
- Check if row minimum element and column maximum element. If it is equal then print saddle point, otherwise no saddle point present in given matrix
Here is the code
//To find the Saddle point of the given matrix
import java.util.Scanner;public class Matrix
{
static void findSaddlePoint(int[][] matrix)
{
for ( int i = 0; i < matrix.length; i++ )
{
int rowMin = matrix[i][0];
int colIndex = 0;
boolean saddlePoint = true;
//Finding the smallest element in ith row
for ( int j = 1; j < matrix [ i ] .length; j++ ){
if ( matrix [ i ][ j ] < rowMin )
{
rowMin = matrix [ i ][ j ];
colIndex = j;
}
}
//Checking rowMin is also the largest element in its column
for ( int j = 0; j < matrix.length; j++ ){
if ( matrix [ j ][ colIndex ] > rowMin )
{
saddlePoint = false;
break;
}
}
if ( saddlePoint )
{
System.out.println("Saddle Point is : "+rowMin);
}
}
}
public static void main(String[] args )
{
Scanner sc = new Scanner(System.in );
System.out.println("Enter the number of rows :");
int rows = sc.nextInt();
System.out.println("Enter the number of columns :");
int cols = sc.nextInt();
int[][] matrix = new int [ rows ][ cols ];
//System.out.println("Enter the elements :");
for ( int i = 0; i < rows; i++ ){
for ( int j = 0; j < cols; j++ )
{
matrix[i][j] = sc.nextInt();
}
}
System.out.println("The Entered matrix is :" );
for ( int i = 0; i < rows; i++ )
{
for ( int j = 0; j < cols; j++ )
{
System.out.print(matrix[i][j]+"\t" );
}
System.out.println();
}
findSaddlePoint(matrix );
sc.close();
}
}