Professional Documents
Culture Documents
Caso Recursivo
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);
}
! F(0)=0
! F(1)=1
! F(n)=F(n-1)+F(n-2) para n > 1.
4
Otro ejemplo: Permutaciones
public class Principal
{
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));
}
}
10
Ordenamiento recursivo: MergeSort
11
12
Ordenamiento recursivo: MergeSort
13
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();
}
15
16
Ultimo ejemplo: Backtracking
public boolean esta_ocupado(int i, int j)
{
if (tab[i][j] > 0)
return true;
else
return false;
}
17
18
Ultimo ejemplo: Backtracking
public class Caballo
{
Tablero tab;
public Caballo(int n)
{
tab = new Tablero(n);
}
19
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
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
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
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