Punto silla en una array

Dada una array de tamaño nxn, la tarea es encontrar el punto de silla de la array. Un punto silla es un elemento de la array tal que es el elemento mínimo en su fila y máximo en su columna. 

Ejemplos: 

Input: Mat[3][3] = { {1, 2, 3},
                  {4, 5, 6},
                  {7, 8, 9}}
Output: 7
7 is minimum in its row and maximum in its column.

Input: Mat[3][3] = {{1, 2, 3},
                    {4, 5, 6},
                    {10, 18, 4}}
Output: No saddle point

Una solución simple es atravesar todos los elementos de la array uno por uno y verificar si el elemento es Saddle Point o no.

Una solución eficiente se basa en los siguientes pasos. 

Recorra todas las filas una por una y haga lo siguiente para cada fila i.  

  1. Encuentre el elemento mínimo de la fila actual y almacene el índice de columna del elemento mínimo.
  2. Compruebe si el elemento mínimo de fila también es máximo en su columna. Usamos el índice de columna almacenado aquí.
  3. En caso afirmativo, entonces el punto de silla continúa hasta el final de la array.

A continuación se muestra la implementación de los pasos anteriores.  

C++

// C++ program to illustrate Saddle point
#include <bits/stdc++.h>
using namespace std;
 
const int MAX = 100;
 
// Function to find saddle point
bool findSaddlePoint(int mat[MAX][MAX], int n)
{
    // Process all rows one by one
    for (int i = 0; i < n; i++)
    {
        // Find the minimum element of row i.
        // Also find column index of the minimum element
        int min_row = mat[i][0], col_ind = 0;
        for (int j = 1; j < n; j++)
        {
            if (min_row > mat[i][j])
            {
                min_row = mat[i][j];
                col_ind = j;
            }
        }
 
        // Check if the minimum element of row is also
        // the maximum element of column or not
        int k;
        for (k = 0; k < n; k++)
 
            // Note that col_ind is fixed
            if (min_row < mat[k][col_ind])
                break;
 
        // If saddle point is present in this row then
        // print it
        if (k == n)
        {
           cout << "Value of Saddle Point " << min_row;
           return true;
        }
    }
 
    // If Saddle Point not found
    return false;
}
 
// Driver code
int main()
{
    int mat[MAX][MAX] = {{1, 2, 3},
                        {4, 5, 6},
                        {7, 8, 9}};
    int n = 3;
    if (findSaddlePoint(mat, n) == false)
       cout << "No Saddle Point ";
    return 0;
}

C

// C program to illustrate Saddle point
#include <stdio.h>
#include <stdbool.h>
 
#define MAX 100
 
// Function to find saddle point
bool findSaddlePoint(int mat[MAX][MAX], int n)
{
    // Process all rows one by one
    for (int i = 0; i < n; i++)
    {
        // Find the minimum element of row i.
        // Also find column index of the minimum element
        int min_row = mat[i][0], col_ind = 0;
        for (int j = 1; j < n; j++)
        {
            if (min_row > mat[i][j])
            {
                min_row = mat[i][j];
                col_ind = j;
            }
        }
 
        // Check if the minimum element of row is also
        // the maximum element of column or not
        int k;
        for (k = 0; k < n; k++)
 
            // Note that col_ind is fixed
            if (min_row < mat[k][col_ind])
                break;
 
        // If saddle point is present in this row then
        // print it
        if (k == n)
        {
           printf("Value of Saddle Point %d",min_row);
           return true;
        }
    }
 
    // If Saddle Point not found
    return false;
}
 
// Driver code
int main()
{
    int mat[MAX][MAX] = {{1, 2, 3},
                        {4, 5, 6},
                        {7, 8, 9}};
    int n = 3;
    if (findSaddlePoint(mat, n) == false)
       printf("No Saddle Point ");
    return 0;
}
 
// This code is contributed by kothavvsaakash.

Java

// Java program to illustrate Saddle point
 
class Test
{
    // Method to find saddle point
    static boolean findSaddlePoint(int mat[][    ], int n)
    {
        // Process all rows one by one
        for (int i = 0; i < n; i++)
        {
            // Find the minimum element of row i.
            // Also find column index of the minimum element
            int min_row = mat[i][0], col_ind = 0;
            for (int j = 1; j < n; j++)
            {
                if (min_row > mat[i][j])
                {
                    min_row = mat[i][j];
                    col_ind = j;
                }
            }
      
            // Check if the minimum element of row is also
            // the maximum element of column or not
            int k;
            for (k = 0; k < n; k++)
      
                // Note that col_ind is fixed
                if (min_row < mat[k][col_ind])
                    break;
      
            // If saddle point is present in this row then
            // print it
            if (k == n)
            {
               System.out.println("Value of Saddle Point " + min_row);
               return true;
            }
        }
      
        // If Saddle Point not found
        return false;
    }
     
    // Driver method
    public static void main(String[] args)
    {
        int mat[][] = {{1, 2, 3},
                      {4, 5, 6},
                     {7, 8, 9}};
         
        int n = 3;
        if (findSaddlePoint(mat, n) == false)
            System.out.println("No Saddle Point ");
    }
}

Python3

# Python3 program to illustrate
# Saddle point
 
# Method to find saddle point
def findSaddlePoint(mat, n):
   
    # Process all rows one
    # by one
    for i in range(n):
       
        # Find the minimum element
        # of row i.
        # Also find column index of
        # the minimum element
        min_row = mat[i][0];
        col_ind = 0;
        for j in range(1, n):
            if (min_row > mat[i][j]):
                min_row = mat[i][j];
                col_ind = j;
 
        # Check if the minimum element
        # of row is also the maximum
        # element of column or not
        k = 0;
        for k in range(n):
 
            # Note that col_ind is fixed
            if (min_row < mat[k][col_ind]):
                break;
            k += 1;
 
        # If saddle point present in this
        # row then print
        if (k == n):
            print("Value of Saddle Point ",
                  min_row);
            return True;
 
    # If Saddle Point found
    return False;
 
# Driver method
if __name__ == '__main__':
   
    mat = [[1, 2, 3],
           [4, 5, 6],
           [7, 8, 9]];
 
    n = 3;
    if (findSaddlePoint(mat, n) ==
        False):
        print("No Saddle Po");
 
# This code is contributed by 29AjayKumar

C#

// C# program to illustrate Saddle point
using System;
 
class GFG {
     
    // Method to find saddle point
    static bool findSaddlePoint(int [,] mat,
                                int n)
    {
         
        // Process all rows one by one
        for (int i = 0; i < n; i++)
        {
             
            // Find the minimum element of
            // row i. Also find column index
            // of the minimum element
            int min_row = mat[i, 0], col_ind = 0;
            for (int j = 1; j < n; j++)
            {
                if (min_row > mat[i, j])
                {
                    min_row = mat[i, j];
                    col_ind = j;
                }
            }
     
            // Check if the minimum element
            // of row is also the maximum
            // element of column or not
            int k;
            for (k = 0; k < n; k++)
     
                // Note that col_ind is fixed
                if (min_row < mat[k, col_ind])
                    break;
     
            // If saddle point is present in this row then
            // print it
            if (k == n)
            {
                Console.WriteLine("Value of Saddle Point "
                                                + min_row);
                return true;
            }
        }
     
        // If Saddle Point not found
        return false;
    }
     
    // Driver code
    public static void Main()
    {
        int [,] mat = {{1, 2, 3},
                       {4, 5, 6},
                       {7, 8, 9}};
         
        int n = 3;
        if (findSaddlePoint(mat, n) == false)
            Console.WriteLine("No Saddle Point ");
    }
}
 
// This code is contributed by KRV.

PHP

<?php
// PHP program to illustrate
// Saddle point
 
$MAX = 100;
 
// Function to find saddle point
function findSaddlePoint( $mat, $n)
{
    // Process all rows one by one
    for ( $i = 0; $i < $n; $i++)
    {
        // Find the minimum element
        // of row i. Also find column
        // index of the minimum element
        $min_row = $mat[$i][0];
        $col_ind = 0;
        for ( $j = 1; $j < $n; $j++)
        {
            if ($min_row > $mat[$i][$j])
            {
                $min_row = $mat[$i][$j];
                $col_ind = $j;
            }
        }
 
        // Check if the minimum element of
        // row is also the maximum element
        // of column or not
        $k;
        for ($k = 0; $k < $n; $k++)
 
            // Note that col_ind is fixed
            if ($min_row < $mat[$k][$col_ind])
                break;
 
        // If saddle point is present in
        // this row then print it
        if ($k == $n)
        {
        echo "Value of Saddle Point " ,
                              $min_row;
        return true;
        }
    }
 
    // If Saddle Point not found
    return false;
}
 
// Driver code
$mat = array(array(1, 2, 3),
             array(4, 5, 6),
             array (7, 8, 9));
$n = 3;
if (findSaddlePoint($mat, $n) == false)
echo "No Saddle Point ";
 
// This code is contributed by anuj_67.
?>

Javascript

<script>
// Javascript program to illustrate Saddle point
 
// Method to find saddle point
function findSaddlePoint(mat, n)
{
 
    // Process all rows one by one
        for (let i = 0; i < n; i++)
        {
         
            // Find the minimum element of row i.
            // Also find column index of the minimum element
            let min_row = mat[i][0], col_ind = 0;
            for (let j = 1; j < n; j++)
            {
                if (min_row > mat[i][j])
                {
                    min_row = mat[i][j];
                    col_ind = j;
                }
            }
       
            // Check if the minimum element of row is also
            // the maximum element of column or not
            let k;
            for (k = 0; k < n; k++)
       
                // Note that col_ind is fixed
                if (min_row < mat[k][col_ind])
                    break;
       
            // If saddle point is present in this row then
            // print it
            if (k == n)
            {
               document.write("Value of Saddle Point " + min_row+"<br>");
               return true;
            }
        }
       
        // If Saddle Point not found
        return false;
}
 
// Driver method
let mat = [[1, 2, 3],
                      [4, 5, 6],
                     [7, 8, 9]];
          
        let n = 3;
        if (findSaddlePoint(mat, n) == false)
            document.write("No Saddle Point ");
 
// This code is contributed by rag2127
</script>
Producción

Value of Saddle Point 7

Ejercicio: 
¿Puede haber más de un punto de silla en una array?

Este artículo es una contribución de Sahil Chhabra (KILLER) . Si te gusta GeeksforGeeks y te gustaría contribuir, también puedes escribir un artículo usando write.geeksforgeeks.org o enviar tu artículo por correo a review-team@geeksforgeeks.org. Vea su artículo que aparece en la página principal de GeeksforGeeks y ayude a otros Geeks.

Publicación traducida automáticamente

Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *