Problem Statement:
You are given a matrix.
You need to find saddle point.
A saddle point is an element in the matrix, is an element such that, the element is minimum in its row and maximum in its column.
Example:
Input:
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
Output:
7
Solution Explanation:
Find the minimum element of the current row, then check the row minimum element is also max in the column.
If yes, return true
Time Complexity: O(n*n)
Space Complexity: O(1)
Code Solution
#include <iostream>
#include <vector>
#include <queue>
#include <stack>
using namespace std;
const int N = 100;
bool solution(int mat[N][N], int len)
{
for (int i = 0; i < len; i++)
{
int rowMin = mat[i][0];
int colIndex = 0;
for (int j = 1; j < len; j++)
{
if (rowMin > mat[i][j])
{
rowMin = mat[i][j];
colIndex = j;
}
}
int k;
for ( k = 0; k < len; k++)
if (rowMin < mat[k][colIndex])
break;
if (k == len)
{
cout << "Saddle Point " << rowMin;
return true;
}
}
return false;
}
int main()
{
int mat[N][N] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
int n = 3;
bool result = solution(mat, n);
if(result == false)
cout << "No Saddle Point ";
return 0;
}
Output
Saddle Point 7