Checking saddle point of Matrx MxM. Saddle point is where value is min in rows and max in columns.
import java.util.Scanner;
class SaddlePoint {
int M;
int[][] A;
public static void main(String[] args) {
SaddlePoint a = new SaddlePoint();
a.input();
a.check();
}
void input() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Order of Square Matrix(M): ");
M = sc.nextInt();
A = new int[M][M];
System.out.println("Enter Matrix of " + M + " by " + M + ": ");
for (int x = 0; x < M; x++)
for (int y = 0; y < M; y++)
A[x][y] = sc.nextInt();
System.out.println("Entered Matrix:-");
for (int x = 0; x < M; x++) {
for (int y = 0; y < M; y++)
System.out.print(A[x][y] + "\t");
System.out.println();
}
sc.close();
}
void check() {
int found = 0;
for (int x = 0; x < M; x++)
for (int y = 0; y < M; y++) {
int vl = A[x][y];
if (min_row(vl, x) && max_col(vl, y)) {
found++;
System.out.println("Saddle Point found at " + x + "," + y + " = " + vl);
}
}
if (found == 0)
System.out.println("No Saddle Point found");
}
boolean min_row(int v, int i) {
int min = A[i][0];
for (int x = 0; x < M; x++)
min = Math.min(min, A[i][x]);
return min == v;
}
boolean max_col(int v, int i) {
int max = A[0][i];
for (int x = 0; x < M; x++)
max = Math.max(max, A[x][i]);
return max == v;
}
}
Name | Type | Uses |
---|---|---|
global | ||
M | int | this is the dimension of the square matrix |
A | int[][] | this is the main matrix for evaluation |
void main( | ||
a | SaddlePoint | Object to call the functions |
void main() | ||
sc | Scanner | Object to take user input |
void check() | ||
found | int | This is the number of saddle points found |
x, y | int | This is the counter variable to itertate over the 2D Array |
boolean min_row() | ||
min | int | this is the minimum value in the row to return |
boolea max_col() | ||
max | int | this is the maximum value in the column to return |