Program to find the saddle point coordinates in a given matrix

Program to find the saddle point coordinates in a given matrix is discussed here.A saddle point is an element of the matrix, which is the minimum element in its row and the maximum in its column.

For example, consider the matrix given below

Mat[3][3] =
1 2 3
4 5 6
7 8 9

Here, 7 is the saddle point because it is the minimum element in its row and maximum element in its column.

saddle point coordinates in a matrix
import java.util.Scanner;

public class Main
{
	public static void main(String[] args)
	{
		int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
		int m = 3,k;
		int min = 0;
		int max = 0;
		int [][]pos = new int[2][2];
		System.out.print(“nThe matrix is n”);
		int i,j;
		for (i = 0; i < m; i++)
			{
				for (j = 0; j < m; j++)
					{
						System.out.print(matrix[i][j] + ” ” );
					}
				System.out.println();
			}
/* find the saddle points in the given matrix */
		for (i = 0; i < m; i++)
			{
				min = matrix[i][0];
				for (j = 0; j < m; j++)
					{
						if (min >= matrix[i][j])
							{
								min = matrix[i][j];
								pos[0][0] = i;
								pos[0][1] = j;
							}
					}
				j = pos[0][1];
				max = matrix[0][j];
				for (k = 0; k < m; k++)
					{
						if (max <= matrix[k][j])
							{
								max = matrix[i][j];
								pos[1][0] = k;
								pos[1][1] = j;
							}
					}
/* saddle point is the minimum of a row and maximum of the column */
				if (min == max) 
					{
						if (pos[0][0] == pos[1][0] &&pos[0][1] == pos[1][1])
							{
								System.out.print(“nSaddle point ( ” + pos[0][0] + “,” + pos[0][1] + ” ) : ” + max + “n”);
							}
					}
				}
		}

}

Output

Enter the square matrix order : 3
Input the matrix : 1 2 3 4 5 6 7 8 9
The matrix is :
1 2 3
4 5 6
7 8 9
Saddle point (3,0) : 7

Leave a Comment

Your email address will not be published. Required fields are marked *