fork download
  1. #NOTE: Use FOUR SPACES (Dont USE TABS) for indentation
  2.  
  3. x, y = [1, 0], [0, 1]
  4.  
  5. def isValid(i, j):
  6. return i >= 0 and i < r and j >= 0 and j < c and visited[i][j] == 0
  7.  
  8. def dfs(i, j, path):
  9. visited[i][j] = 1
  10. if i == r - 1 and j == c - 1:
  11. ans.append(path)
  12. for dir_ in range(2):
  13. temp_i, temp_j = i + x[dir_], j + y[dir_]
  14. if isValid(temp_i, temp_j):
  15. dfs(temp_i, temp_j, path + str(mat[temp_i][temp_j]))
  16. visited[i][j] = 0
  17.  
  18. if __name__ == "__main__":
  19. t = int(input().strip())
  20. for ti in range(t):
  21. ans = []
  22. rc = input().strip().split(' ')
  23. r = int(rc[0])
  24. c = int(rc[1])
  25. visited = [[0] * c for _ in range(r)]
  26. mat = [] # Empty List of Lists
  27. for ri in range(r):
  28. rowList = list(map(int, input().strip().split(' ')))
  29. mat.append(rowList)
  30. dfs(0, 0, "1")
  31. for i in ans:
  32. print(*i)
  33. print()
Success #stdin #stdout 0.03s 9300KB
stdin
2
3 3
1 2 3
4 5 6
7 8 9
2 3
1 2 4
3 7 6
stdout
1 4 7 8 9
1 4 5 8 9
1 4 5 6 9
1 2 5 8 9
1 2 5 6 9
1 2 3 6 9

1 3 7 6
1 2 7 6
1 2 4 6