Created
October 19, 2015 02:50
-
-
Save Haylin-chama/a3d6540bf0ce129ee508 to your computer and use it in GitHub Desktop.
Dijkstra's algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Dijkstra | |
#Aplicación del algoritmo visto en clases | |
#0. Validaciones | |
def Validar(): | |
a=input("Valor: ") | |
if a.isdigit(): #Función para corroborar que una línea de caracteres corresponden exclusivamente a números | |
#Es una función bool de verdadero o falso | |
return int(a) | |
else: | |
print ("Ingrese un valor numérico.") | |
return Validar() | |
#Funcion que se llama a si misma en caso que no sea una linea | |
def Opcion(): | |
a=input("Respuesta: ") | |
if a=='S' or a=="s": | |
return 1 | |
if a=="N" or a=="n": | |
return 0 | |
else: | |
print ("Error. Ingrese S o N.") | |
Opcion() | |
#1. Crear la matriz | |
def CrearMatrizdeCosto(M): | |
print ("Ingrese numero de vertices: ") #pide la cantidad de vertices | |
v=Validar()#Para el algoritmo se necesitan nombres numericos y que esten ordenados | |
for i in range(int(v)): | |
lista=[] | |
print ("Pesos para el vertice",i+1) | |
for j in range(v): | |
print ("con la arista ",j+1,": ") | |
x=Validar() | |
lista.extend([x]) | |
M.extend([lista]) | |
return M,v | |
#2. Las funciones de dijkstra | |
#Encontrando y retornando la posicion del valor minimo | |
def W(vector): | |
w=inf | |
for i in range(len(vector)): | |
if vector[i]<w: | |
w=vector[i] | |
posicion=i | |
return posicion | |
#Funcion V-S | |
def VectorVS(D,S): | |
for i in range(len(S)): | |
x=S[i] | |
D.remove(x) | |
return W(D) | |
#Copiando valores de la primera fila de la matriz G al vector D | |
def D(G,S): | |
D=G[0] | |
return VectorVS(D,S) | |
#Iniciando algoritmo | |
def Dijkstra(G,n): | |
print("DIJKSTRA") | |
S=[0] | |
D=[] | |
D=G[2:n] | |
print ('D: ',D) | |
for i in range(1,n-1,1): | |
print ('Segundo for') | |
funcion(G,S) | |
#for each vertex v in V-S hacer | |
#D[v]=min(D[v],D[w]+C[w,v]) | |
print('fin') | |
#4. Menu | |
def main(): | |
MatrizDeCosto=[] | |
Vertices=0 | |
while True: | |
print ('') | |
print ("a) Crear grafo etiquetado") | |
print ("b) Dijkstra") | |
print ("S) Salir") | |
opc=str.lower(input("Ingrese una opcion: ")) | |
if opc=='a' or opc=='A': | |
MatrizDeCosto,Vertices=CrearMatrizdeCosto(MatrizDeCosto) | |
print (MatrizDeCosto) | |
if opc=='b' or opc=='B': | |
print("Matriz de costo: ",MatrizDeCosto) | |
print("Vertices: ",Vertices) | |
if Vertices==0: | |
print ("Se necesita crear un grafo primero. ") | |
else: | |
Dijkstra(MatrizDeCosto,Vertices) | |
if opc=='s' or opc=='S': | |
break | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment