function route(grid) {
  const rows = grid.length;
  const cols = rows ? grid[0].length : 0;
  const dr = [-1, 1, 0, 0];
  const dc = [0, 0, -1, 1];
  const moves = "UDLR";
  const states = rows * cols * 5;
  const dist = new Array(states).fill(Infinity);
  const parent = new Array(states).fill(-1);
  const done = new Array(states).fill(false);
  let start = -1;
  let goal = -1;

  for (let r = 0; r < rows; r++) {
    for (let c = 0; c < cols; c++) {
      if (grid[r][c] === "S") start = r * cols + c;
      if (grid[r][c] === "G") goal = r * cols + c;
    }
  }
  if (start < 0 || goal < 0) return null;

  dist[start * 5 + 4] = 0;

  for (;;) {
    let current = -1;
    for (let i = 0; i < states; i++) {
      if (!done[i] && dist[i] < Infinity &&
          (current < 0 || dist[i] < dist[current])) {
        current = i;
      }
    }
    if (current < 0) return null;

    const cell = Math.floor(current / 5);
    const direction = current % 5;
    if (cell === goal) {
      let result = "";
      for (let i = current; parent[i] >= 0; i = parent[i]) {
        result = moves[i % 5] + result;
      }
      return result;
    }

    done[current] = true;
    const r = Math.floor(cell / cols);
    const c = cell % cols;

    for (let d = 0; d < 4; d++) {
      const nr = r + dr[d];
      const nc = c + dc[d];
      if (nr < 0 || nr >= rows || nc < 0 || nc >= cols ||
          grid[nr][nc] === "#") continue;

      const next = (nr * cols + nc) * 5 + d;
      const cost = dist[current] + 1000 +
        (direction !== 4 && direction !== d ? 1 : 0);
      if (cost < dist[next]) {
        dist[next] = cost;
        parent[next] = current;
      }
    }
  }
}