How to Find Saddle Point of a Matrix in Java
Today we are going to learn how to find the saddle point of a matrix in Java. As we all know a matrix is a 2-Dimensional array and in it, Saddle point is that element of the matrix which is lowest in its row but the highest in its column.
Saddle Point of a Matrix in Java
There are many ways to solve this problem, One of the solutions is provided here.
Following are the steps to follow-
1. Traverse the row and find the smallest number. Save its column number in a variable.
2. Now traverse the same column check if the row ‘s smallest number is greatest in its column.
3. If yes print the number , if no check for next row.
4. If no such point is there in the array, print no saddle point.
here is the code for the same.
import java.util.Scanner; /** * @author darshna * */ public class Saddle_point { public static void main(String[] args) { Scanner s = new Scanner(System.in); System.out.println("enter the size of 2d matrix"); int n = s.nextInt(); int arr[][] = new int[n][n]; System.out.println("enter the array:-"); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { arr[i][j] = s.nextInt(); } int col_max = 0; for (int i = 0; i < n; i++) { int row_min = arr[i][0]; //smallest of row int col = 0; for (int j = 1; j < n; j++) { if (arr[i][j] < row_min) { row_min = arr[i][j]; col = j; } } for (int k = 0; k < n; k++) { if (row_min < arr[k][col]) { col_max = 0; break; } else col_max = row_min; } if (col_max != 0) System.out.println("saddle point " + col_max); } } }
Output:-
enter the size of 2d matrix 3 enter the array:- 1 2 3 4 5 6 7 8 9 saddle point 7
Hope you understand the code.
You may also read:
- Shift elements of an array to Left in Java
- Java program to display upper triangular matrix’
- To check whether a given matrix is Symmetric or not in Java
- How to find a Transpose of a matrix by using java
Can you give variable description and algorithm for this program