Hola,
Si tiene que ordenar la matriz 2D que está utilizando, utilice la técnica Divide and Conquer para encontrar el elemento.
Aquí el procedimiento básico para resolver la matriz 2D: –
1) Comience con el elemento superior derecho
2) Bucle: compare este elemento e con x
… .I) si son iguales, devuelva su posición
… ii) e x luego muévalo hacia la izquierda (si está fuera del límite de la matriz, luego rompa el retorno falso)
3) repita el i), ii) y iii) hasta que encuentre el elemento o devuelva falso
- ¿Cuál es la forma correcta de leer CLRS (Introducción a los algoritmos)?
- Cómo entender un algoritmo de búsqueda CSP
- ¿Cuáles son las buenas implementaciones de búfer circular sin bloqueo en Java?
- ¿Todos los NP-HARD que son decidibles también son NP-Complete?
- ¿Cuáles son algunos de los buenos problemas de retroceso?
Gracias a devendraiiit por sugerir el siguiente enfoque.
Implementación:
// C program to search an element in row-wise
// and column-wise sorted matrix
#include
/* Searches the element x in mat[][]. If the
element is found, then prints its position
and returns true, otherwise prints "not found"
and returns false */
int
search(int
mat[4][4], int
n, int
x)
{
int
i = 0, j = n-1; //set indexes for top right element
i = 0, j = n-1; //set indexes for top right element
while
( i = 0 )
{
if
( mat[i][j] == x )
{
printf("\n Found at %d, %d", i, j);
return
1;
}
if
( mat[i][j] > x )
j--;
else
// if mat[i][j] < x
i++;
}
printf("\n Element not found");
return
0; // if ( i==n || j== -1 )
0; // if ( i==n || j== -1 )
}
// driver program to test above function
int
main()
{
int
mat[4][4] = { {10, 20, 30, 40},
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50},
};
search(mat, 4, 29);
return
0;
}