You are on page 1of 14

¿Qué es recursividad?

! Función que se define en términos de si misma.


• Ejemplo: el valor de la función para el argumento n puede
definirse en términos del argumento n-1 (o alguno
anterior).
• Siempre debe existir un caso base:
Caso Base

Caso Recursivo

Ejemplo de recursividad en Java


public static int factorial(int n)
{
if (n == 0 || n ==1)
return(1);
else
return(n*factorial(n-1));
}

2
Recursividad puede eliminarse
public static int factorial2(int n)
{
int i, fact = 1;
for (i=2; i<=n; i++)
fact = fact * i;
return(fact);
}

! Eliminar la recursividad, normalmente tiene dos


efectos contrapuestos:
• Aumenta la eficiencia (menos tiempo de ejecución)
• Dificulta la programación (más tiempo de programación)

Serie de Fibonacci con y sin recursividad

! F(0)=0
! F(1)=1
! F(n)=F(n-1)+F(n-2) para n > 1.

4
Otro ejemplo: Permutaciones
public class Principal
{

public static void main(String[] args)


{
permutar("abc");
}

public static void permutar(String s)


{
String nulo = "";
permutar(nulo, s);
}

Otro ejemplo: Permutaciones


public static void permutar(String listo, String perm)
{
if (perm.length() == 1)
Usuario.mensajeConsola(listo + perm);
else
{
int i;
String nuevo_listo, nuevo_perm;
for (i = 0; i < perm.length(); i++)
{
nuevo_listo = listo + perm.charAt(i);
nuevo_perm = eliminar(perm, i);
permutar(nuevo_listo, nuevo_perm);
}
}
}

6
Otro ejemplo: Permutaciones
public static String eliminar(String s, int pos)
{
if (pos == 0)
return s.substring(1);
else if (pos == s.length() - 1)
return s.substring(0,s.length() - 1);
else
return s.substring(0,pos) + s.substring(pos+1);
}
}

Permutaciones: Resultado

abc
acb
bac
bca
cab
cba

8
Ordenamiento recursivo: MergeSort
public class Principal
{
public static int[] mergeSort(int[] arreglo)
{
if (arreglo.length == 1)
return(arreglo);
else
{
int[] primera_ordenada, segunda_ordenada;
primera_ordenada = mergeSort(primera_mitad(arreglo));
segunda_ordenada = mergeSort(segunda_mitad(arreglo));
return(mezclar(primera_ordenada, segunda_ordenada));
}
}

Ordenamiento recursivo: MergeSort


public static int[] mezclar(int[] primera, int[] segunda)
{
int[] solucion = new int[primera.length + segunda.length];
int i = 0, j = 0, k = 0;

while (i < primera.length || j < segunda.length)


{
if (i == primera.length)
{
solucion[k] = segunda[j];
j++;
}
else if (j == segunda.length)
{
solucion[k] = primera[i];
i++;
}

10
Ordenamiento recursivo: MergeSort

else if (primera[i] < segunda[j])


{
solucion[k] = primera[i];
i++;
}
else
{
solucion[k] = segunda[j];
j++;
}
k++;
}
return(solucion);
}

11

Ordenamiento recursivo: MergeSort

public static int[] primera_mitad(int[] arreglo)


{
int i, mitad = arreglo.length/2;
int[] primera = new int[mitad];
for(i = 0; i < mitad; i++)
primera[i] = arreglo[i];
return(primera);
}

12
Ordenamiento recursivo: MergeSort

public static int[] segunda_mitad(int[] arreglo)


{
int i, mitad = arreglo.length/2;
int[] segunda;
if (arreglo.length%2 == 0)
{
segunda = new int[mitad];
for(i = 0; i < mitad; i++)
segunda[i] = arreglo[i + mitad];
}
else
{
segunda = new int[mitad + 1];
for(i = 0; i < mitad + 1; i++)
segunda[i] = arreglo[i + mitad];
}
return(segunda);
}

13

Ordenamiento recursivo: MergeSort

public static void imprimir(int[] arreglo)


{
int i;
String s = "";
for(i = 0; i<arreglo.length; i++)
s = s + arreglo[i] + "\t";
Usuario.mensajeConsola(s);
}

public static void main(String[] args)


{
int[] a = {2, 5, 7, 9, 8, 1, 10, 2, 5, -10, 11, 0};
int[] b;

imprimir(a);
b = mergeSort(a);
imprimir(b);
}
}

14
Ultimo ejemplo: Backtracking
public class Tablero
{
private int[][] tab;

public Tablero(int n)
{
tab = new int[n][n];
inicializar();
}

public void inicializar()


{
int i,j;
for (i = 0; i < tab.length; i++)
for (j = 0; j < tab.length; j++)
tab[i][j] = 0;
}

15

Ultimo ejemplo: Backtracking


public void imprimir()
{
String s;
int i,j;

for (i = 0; i < tab.length; i++)


{
s = "";
for (j = 0; j < tab.length; j++)
s = s + "\t" + tab[i][j];
Usuario.mensajeConsola(s);
}
}

16
Ultimo ejemplo: Backtracking
public boolean esta_ocupado(int i, int j)
{
if (tab[i][j] > 0)
return true;
else
return false;
}

public void insertar(int i, int j, int num)


{
tab[i][j] = num;
}

17

Ultimo ejemplo: Backtracking


public void eliminar(int i, int j)
{
tab[i][j] = 0;
}

public int numero_casillas()


{
return tab.length;
}
}

18
Ultimo ejemplo: Backtracking
public class Caballo
{
Tablero tab;

public Caballo(int n)
{
tab = new Tablero(n);
}

public void imprimir_recorrido()


{
tab.imprimir();
}

19

Ultimo ejemplo: Backtracking


private boolean posible(int i, int j, int movida, int[] pos)
{
if (movida == 1 && 0 <= i-2 && 0 <= j-1)
{
pos[0] = i-2;
pos[1] = j-1;
return true;
}
else if (movida == 2 && 0 <= i-2 &&
j+1 < tab.numero_casillas())
{
pos[0] = i-2;
pos[1] = j+1;
return true;
}

20
Ultimo ejemplo: Backtracking
else if (movida == 3 && 0 <= i-1 &&
j+2 < tab.numero_casillas())
{
pos[0] = i-1;
pos[1] = j+2;
return true;
}
else if (movida == 4 && i+1 < tab.numero_casillas() &&
j+2 < tab.numero_casillas())
{
pos[0] = i+1;
pos[1] = j+2;
return true;
}

21

Ultimo ejemplo: Backtracking


else if (movida == 5 && i+2 < tab.numero_casillas() &&
j+1 < tab.numero_casillas())
{
pos[0] = i+2;
pos[1] = j+1;
return true;
}
else if (movida == 6 && i+2 < tab.numero_casillas() &&
0 <= j-1)
{
pos[0] = i+2;
pos[1] = j-1;
return true;
}

22
Ultimo ejemplo: Backtracking
else if (movida == 7 && i+1 < tab.numero_casillas() &&
0 <= j-2)
{
pos[0] = i+1;
pos[1] = j-2;
return true;
}
else if (movida == 8 && 0 <= i-1 && 0 <= j-2)
{
pos[0] = i-1;
pos[1] = j-2;
return true;
}
else
return false;
}

23

Ultimo ejemplo: Backtracking


public boolean recorrer(int i, int j, int mov)
{
tab.inicializar();
tab.insertar(i, j, 1);
return recorrer(i, j, 2, mov);
}

private boolean recorrer(int i, int j, int n, int mov)


{
if (n > mov)
return true;
else

24
Ultimo ejemplo: Backtracking
{
int k; int[] pos = new int[2];
for (k = 1; k <= 8; k++)
if (posible(i,j,k,pos))
if (!tab.esta_ocupado(pos[0], pos[1]))
{
tab.insertar(pos[0], pos[1], n);
if (recorrer(pos[0], pos[1], n+1, mov))
return true;
else
tab.eliminar(pos[0],pos[1]);
}
return false;
}
}
}

25

Ultimo ejemplo: Backtracking


public class Principal
{
public static void main(String[] args)
{
Caballo c = new Caballo(8);

if (c.recorrer(0, 1, 64))
{
Usuario.mensajeConsola("Recorrido:");
c.imprimir_recorrido();
}
else
Usuario.mensaje(
"No se puede hacer el recorrido");
}
}
26
Ejemplo backtracking: Resultado

28 1 30 13 20 3 16 7
31 40 27 2 15 6 21 4
56 29 14 39 12 19 8 17
41 32 55 26 47 24 5 22
54 57 48 33 38 11 18 9
49 42 51 46 25 34 23 62
58 53 44 37 60 63 10 35
43 50 59 52 45 36 61 64

27

You might also like