Saddle Point
Given a matrix of n x n size, the task is to find saddle point of the matrix. A saddle point is an element of the matrix such that it is the minimum element in its row and maximum in its column.
Examples:
Input: Mat[3][3] = { {1, 2, 3},
{4, 5, 6},
{7, 8, 9}}
Output: 7
7 is minimum in its row and maximum in its column.
Input: Mat[3][3] = {{1, 2, 3},
{4, 5, 6},
{10, 18, 4}}
Output: No saddle point
import java.io.*;
class SaddlePoint
{
public void displayPoint()throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter no of rows: ");
int r=Integer.parseInt(br.readLine());
System.out.print("Enter no of columns: ");
int c=Integer.parseInt(br.readLine());
int [][]arr=new int[r][c];
int stR=0; //To store the row index of the largest no in the entire array.
int t=0;
for(int i=0;i<r;i++)
{
System.out.print("Enter a value for row "+i);
for(int j=0;j<c;j++)
arr[i][j]=Integer.parseInt(br.readLine());
}
int lowest=0; //To store the lowest number in the row containing the largest number.
System.out.print("\f");
for(int q=0;q<r;q++)
{
for(int y=0;y<c;y++)
System.out.print(arr[q][y]+" ");
System.out.println();
}
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
if(arr[i][j]>t)
{
t=arr[i][j];
stR=i; //Row number is now stored which contains the largest number.
}
}
}
int stC=0;//To store the column index where the smallest number is located in the row of the largest number.
int dag=0;
for(int i=0;i<(c-1);i++)
{
lowest=Math.min(arr[stR][0],arr[stR][i]);
for(int h=0;h<c;h++)
{
if(arr[stR][h]==lowest)
stC=h;
}
}
int t2=0;
for(int dx=0;dx<r;dx++)
{
if(arr[dx][stC]>t2)
t2=arr[dx][stC];
}
if(arr[stR][stC]==t2)
System.out.println("Shaddel Point is found at "+(stR+1)+" row and "+(stC+1)+" column");
else
System.out.println("Shaddel Point is not found in the entire array");
}
}
Comments
Post a Comment