fork(1) download
  1. pad = [
  2. "123",
  3. "456",
  4. "789",
  5. " 0 "
  6. ]
  7.  
  8. def valid(i, j):
  9. if i >= 4 or i < 0 or j < 0 or j >= 3:
  10. return False
  11. return (pad[i][j] != ' ')
  12.  
  13. delta_x = [-1, 1, 0, 0]
  14. delta_y = [0, 0, -1, 1]
  15.  
  16. def f(d, n):
  17. if n == 1:
  18. return [d]
  19. if n <= 0:
  20. return []
  21.  
  22. x = None; y = None
  23.  
  24. # The following line of code can be replaced by a dict lookup which
  25. # stores the indices of every digit, say { 5: (1, 1), 1: (0, 0) .. }
  26. for i in range(0,4):
  27. for j in range(0,3):
  28. if pad[i][j] == str(d):
  29. x = i; y = j
  30.  
  31. digits = []
  32. for i in range(0,4):
  33. next_x = x + delta_x[i]
  34. next_y = y + delta_y[i]
  35. if valid(next_x, next_y):
  36. digits.extend(f(pad[next_x][next_y], n - 1))
  37.  
  38. return [str(d) + str(w) for w in digits]
  39.  
  40. print(f(5, 1))
  41. print(f(1, 3))
  42. print(f(0, 3))
Success #stdin #stdout 0.02s 27712KB
stdin
Standard input is empty
stdout
[5]
['141', '147', '145', '125', '121', '123']
['085', '080', '087', '089']