input: from typing import List
  
  def solve_maze(grid: List[List[int]], n: int, m: int) -> List[int]:
      """ Given a maze represented by a 2D grid of size n x m, where each cell is either 0 (wall) or 1 (path),
      this function finds and returns a list of integers representing the shortest path from the top-left corner (0,0)
      to the bottom-right corner (n-1, m-1) if it exists. If there is no path, it returns an empty list.
      >>> solve_maze([[1, 0, 1], [1, 1, 1], [0, 0, 1]], 3, 3)
      [0, 0, 1, 1, 2]
      >>> solve_maze([[1, 0, 0], [1, 1, 0], [0, 1, 1]], 3, 3)
      [0, 0, 1, 1, 2, 2]
      >>> solve_maze([[1, 0, 0], [0, 1, 0], [0, 0, 1]], 3, 3)
      []
      """
output:     from collections import deque
  
      def is_valid(x, y):
          return 0 <= x < n and 0 <= y < m and grid[x][y] == 1
  
      directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
      queue = deque([(0, 0, [])])
      visited = set()
      visited.add((0, 0))
  
      while queue:
          x, y, path = queue.popleft()
          path = path + [x * m + y]
  
          if x == n - 1 and y == m - 1:
              return path
  
          for dx, dy in directions:
              nx, ny = x + dx, y + dy
              if is_valid(nx, ny) and (nx, ny) not in visited:
                  visited.add((nx, ny))
                  queue.append((nx, ny, path))
  
      return []