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.

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("Enter 2D Array Data :");
        for (i = 0; i < num; i++) {
            for (j = 0; j < num; j++) {
                a[i][j] = sc.nextInt();
            }
        }

        System.out.print("Elements 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 :1 2 3 4 5 6 7 8 9
Elements of The 2D array is :
 1 2 3
 4 5 6
 7 8 9
Value of Saddle Point :7