input: def shortestPath(grid, k):
      """
      Consider a grid composed of N rows and N columns (N >= 2) and a positive integer k.
      Each cell within the grid features a unique value from the set [1, N * N], and every
      value appears exactly once within the grid.
  
      The task is to determine the shortest path of length k within the grid. The path can
      commence from any cell, and each move can transition to an adjacent cell sharing a
      side with the current cell.
      Note that a path of length k involves visiting precisely k cells (not necessarily distinct).
      Movement outside the grid boundary is not permitted.
      A path A (of length k) is deemed smaller compared to a path B (of length k) if, when
      comparing the ordered lists of values within paths A and B (denoted as list_A and list_B),
      list_A is lexicographically smaller than list_B. Specifically, there exists an index i (1 <= i <= k)
      such that list_A[i] < list_B[i], and for any index j (1 <= j < i), we have
      list_A[j] = list_B[j].
      It is guaranteed that there is a unique solution.
      Return the ordered list of values encountered in the cells of the minimum path.
  
      Examples:
  
          Input: grid = [ [1,2,3], [4,5,6], [7,8,9]], k = 3
          Output: [1, 2, 1]
  
          Input: grid = [ [5,9,3], [4,1,6], [7,8,2]], k = 1
          Output: [1]
      """
output:     from collections import deque
      import heapq
      
      def get_neighbors(x, y, n):
          for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
              nx, ny = x + dx, y + dy
              if 0 <= nx < n and 0 <= ny < n:
                  yield nx, ny
  
      n = len(grid)
      best = []
      
      for i in range(n):
          for j in range(n):
              queue = [(grid[i][j], [(i,j)])]
              
              while queue:
                  current_path_value, path = heapq.heappop(queue)
                  
                  if len(path) == k:
                      best.append([grid[x][y] for x, y in path])
                  elif len(path) < k:
                      last_x, last_y = path[-1]
                      for nx, ny in get_neighbors(last_x, last_y, n):
                          heapq.heappush(queue, (grid[nx][ny], path + [(nx, ny)]))
                          
      best.sort()
      
      return best[0]