input: from typing import List
  
  
  def find_maze_solution(matrix: List[List[int]]) -> List[int]:
      """ Given a matrix representing a maze, where 1 represents a valid path and 0
      represents a wall, find a path from the top-left corner (0,0) to the bottom-right corner (n-1, m-1).
      The function should return a list of integers representing the path length from the start to each cell
      in the path until the end.
      
      >>> find_maze_solution([[1, 0, 1], [1, 1, 1], [0, 1, 1]])
      [0, 1, 2, 3]
      >>> find_maze_solution([[1, 0, 0], [1, 1, 0], [0, 1, 1]])
      [0, 1, 2, 3]
      """
output:     rows, cols = len(matrix), len(matrix[0])
      if rows == 0 or cols == 0:
          return []
  
      directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
      queue = [(0, 0, 0)]
      visited = set()
      visited.add((0, 0))
      path_lengths = {}
  
      while queue:
          x, y, dist = queue.pop(0)
          path_lengths[(x, y)] = dist
  
          if x == rows - 1 and y == cols - 1:
              break
  
          for dx, dy in directions:
              nx, ny = x + dx, y + dy
              if 0 <= nx < rows and 0 <= ny < cols and (nx, ny) not in visited and matrix[nx][ny] == 1:
                  visited.add((nx, ny))
                  queue.append((nx, ny, dist + 1))
  
      if (rows - 1, cols - 1) not in path_lengths:
          return []
  
      path = []
      x, y = rows - 1, cols - 1
      while (x, y) != (0, 0):
          path.append(path_lengths[(x, y)])
          for dx, dy in directions:
              nx, ny = x + dx, y + dy
              if 0 <= nx < rows and 0 <= ny < cols and (nx, ny) in path_lengths and path_lengths[(nx, ny)] == path_lengths[(x, y)] - 1:
                  x, y = nx, ny
                  break
      path.append(0)
      return path[::-1]