How to solve this problem?

I was solving the following problem but couldn't even think how to optimize it:

Description

Given a maze maze of n*m, in the maze, . indicates empty space, S indicates the start point, T indicates the end point, * means the obstacle, and the numbers 0~9 indicates different treasures. Your journey will finish when you arrive at the end point with all treasures. Please output the minimal number of steps you will take.If you can never finish your journey, output -1

Given a maze, whose size is n * m. In the maze:

    . indicates empty space
    S indicates the start point
    T indicates the end point
    * means the obstacle
    The numbers 0~9 indicates different treasures

Starting from S, how many steps at least do you need to reach T with getting all the treasures? If there
is no solution, return -1.

Note

  1. n, m <= 50
  2. The number will be continuous, and start from 0. Each number appears at most once.
  3. You can stand at all points on the map except obstacles.
  4. The end point can be treated as an empty space before all the treasures have been collected.

Examples
Example 1:

Input["T1S.",".*0*","....","..*."]
Output4
Explanation(0,2)->(1,2)->(0,2)->(0,1)->(0,0)

Example 2:

Input["1*S.","..0.","T..."]
Output6
Explanation(0,2)->(1,2)->(1,1)->(1,0)->(0,0)->(1,0)->(2,0)
Comments (4)