fork download
  1. def esValido(n, m, i, j, lab):
  2. return 0 <= i < m and 0 <= j < n and lab[i][j] == 0
  3.  
  4. def recorroLab(lab):
  5. m, n = len(lab), len(lab[0])
  6. movs = []
  7. recorrido(lab, m, n, 0, 0, movs, "")
  8. if movs: # Verifica si se encontró al menos un camino
  9. return min(movs, key=len) # Devuelve el camino más corto
  10. else:
  11. return None # Si no hay camino, devuelve None
  12.  
  13. def recorrido(lab, m, n, i, j, movs, actual):
  14. if not esValido(n, m, i, j, lab):
  15. return
  16. if i == m - 1 and j == n - 1:
  17. movs.append(actual)
  18. return
  19. lab[i][j] = 1
  20. recorrido(lab, m, n, i + 1, j, movs, actual + "D")
  21. recorrido(lab, m, n, i - 1, j, movs, actual + "U")
  22. recorrido(lab, m, n, i, j - 1, movs, actual + "L")
  23. recorrido(lab, m, n, i, j + 1, movs, actual + "R")
  24. lab[i][j] = 0
  25.  
  26. laberinto = [
  27. [0, 0, 1, 0, 0],
  28. [1, 0, 1, 0, 1],
  29. [1, 0, 0, 0, 1],
  30. [1, 0, 0, 0, 0],
  31. [0, 1, 0, 1, 0]
  32. ]
  33.  
  34. print(recorroLab(laberinto))
  35.  
Success #stdin #stdout 0.04s 9472KB
stdin
Standard input is empty
stdout
RDDDRRRD