Java Program to find saddle point in a matrix


In this program, You will learn how to find saddle point in a matrix in Java.


4 5 6

7 8 9

5 1 3

Saddle Point :7


Example: How to find saddle point in a matrix in Java

Run it Now
import java.util.Scanner;

class Main {
    public static void main(String args[]) {

        int i, j, num;
        int sm, p, large, f = 1;

        int a[][] = new int[100][100];
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter Size of Matrix :");
        num = sc.nextInt();

        System.out.print("\nEnter 2D Array Data :");
        for (i = 0; i < num; i++) {
            for (j = 0; j < num; j++) {
                a[i][j] = sc.nextInt();
            }
        }

        System.out.print("\nElements of The 2D array is :");
        for (i = 0; i < num; i++) {
            System.out.print("\n");
            for (j = 0; j < num; j++) {
                System.out.print(" " + a[i][j]);
            }
        }

        /* Logic start here */
        for (i = 0; i < num; i++) {
            p = 0;
            sm = a[i][0];
            for (j = 0; j < num; j++) {
                if (sm > a[i][j]) {
                    sm = a[i][j];
                    p=j;
                }
            }

            large = 0;
            for (j = 0; j < num; j++) {
                if (large < a[j][p]) {
                    large = a[j][p];
                }
            }

            if (sm == large) {
                System.out.print("\nValue of Saddle Point :" + sm);
                f = 0;
            }
        }

        if (f > 0) {
            System.out.print("\nNo Saddle Point ");
        }

    }
}

Output:

Enter Size of Matrix :3
Enter 2D Array Data :4 5 6 7 8 9 5 1 3
Elements of The 2D array is :
 4 5 6
 7 8 9
 5 1 3
Value of Saddle Point :7