**Task:**
Generate a challenging test input that exposes the bug in the buggy code of the algorithm problem:
Algorithm Problem:
Title: Trapped in the Witch's Labyrinth
time_limit_ms: 3000
memory_limit_mb: 256
Description: In the fourth labor of Rostam, the legendary hero from the Shahnameh, an old witch has created a magical maze to trap him. The maze is a rectangular grid consisting of $$$n$$$ rows and $$$m$$$ columns. Each cell in the maze points in a specific direction: up, down, left, or right. The witch has enchanted Rostam so that whenever he is in a cell, he will move to the next cell in the direction indicated by that cell.

If Rostam eventually exits the maze, he will be freed from the witch's enchantment and will defeat her. However, if he remains trapped within the maze forever, he will never escape.

The witch has not yet determined the directions for all the cells. She wants to assign directions to the unspecified cells in such a way that the number of starting cells from which Rostam will be trapped forever is maximized. Your task is to find the maximum number of starting cells which make Rostam trapped.

Input: The first line of the input contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$), the number of test cases.

For each test case:

- The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 1000$$$), representing the number of rows and columns in the maze.
- Each of the next $$$n$$$ lines contains a string of $$$m$$$ characters representing the directions in the maze. Each character is one of the following:   U (up)  D (down)  L (left)  R (right)  ? (unspecified direction)

It's guaranteed that the sum of $$$n \cdot m$$$ over all test cases is at most $$$10^6$$$.

Output: For each test case, print a single integer, the maximum number of starting cells from which Rostam will be trapped forever after assigning directions to the unspecified cells optimally.

Examples:
input:
3
3 3
UUU
L?R
DDD
2 3
???
???
3 3
?U?
R?L
RDL
output:
0
6
5

Note: In the first test case, all of the cells will be good no matter what you do.

In the second test case, if you assign the ?s like the picture below, all of the cells will be bad:

In the third test case, if you assign the ?s like the picture below, you will have $$$5$$$ bad cells (red-shaded cells):

Buggy Code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Scanner;

public class Solution {
	public static void main(String[] args) {
		Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
		int t = in.nextInt();
		for (int i = 0; i < t; i++) {
			int n = in.nextInt();
			int m = in.nextInt();
			in.nextLine();
			char[][] maze = getCharArr(in, n, m);
			String s = in.nextLine();
			int r = solve(n, m, maze);
			System.out.println(r);

		}

		in.close();
	}

	private static int solve(int n, int m, char[][] maze) {
		int[][] directions = { { 0, 1 }, { 0, -1 }, { -1, 0 }, { 1, 0 } };
		Map<Character, int[]> directionToOffs = new HashMap<>();
		directionToOffs.put('U', directions[3]);
		directionToOffs.put('D', directions[2]);
		directionToOffs.put('L', directions[1]);
		directionToOffs.put('R', directions[0]);
		int[][] escapable = new int[n][m];

		Queue<int[]> q = new LinkedList<>();
		for (int i = 0; i < n; i++) {
			Arrays.fill(escapable[i], 4);
			if (maze[i][0] == 'L' && escapable[i][0] > 0) {
				escapable[i][0] = 0;
				q.offer(new int[] { i, 0 });
			}
			if (maze[i][m - 1] == 'R' && escapable[i][m - 1] > 0) {
				escapable[i][m - 1] = 0;
				q.offer(new int[] { i, m - 1 });
			}
		}
		for (int i = 0; i < m; i++) {
			if (maze[0][i] == 'U' && escapable[0][i] > 0) {
				escapable[0][i] = 0;
				q.offer(new int[] { 0, i });
			}
			if (maze[n - 1][i] == 'D' && escapable[n - 1][i] > 0) {
				escapable[n - 1][i] = 0;
				q.offer(new int[] { n - 1, i });
			}
		}
		while (!q.isEmpty()) {
			int[] cur = q.poll();
			for (int[] d : directions) {
				int[] nxt = new int[] { d[0] + cur[0], d[1] + cur[1] };
				if (0 <= nxt[0] && nxt[0] < n && 0 <= nxt[1] && nxt[1] < m) {
					if (maze[nxt[0]][nxt[1]] == '?') {
						escapable[nxt[0]][nxt[1]]--;
						if (escapable[nxt[0]][nxt[1]] == 0) {
							q.offer(nxt);
						}
					} else {
						int[] offs = directionToOffs.get(maze[nxt[0]][nxt[1]]);
						if (cur[0] == offs[0] + nxt[0] && cur[1] == offs[1] + nxt[1] && escapable[nxt[0]][nxt[1]] > 0) {
							escapable[nxt[0]][nxt[1]] = 0;
							q.offer(nxt);
						}
					}

				}
			}
		}
		int ans = 0;
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				if (escapable[i][j] != 0) {
					ans++;
				}
			}
		}
		return ans;
	}

	static long mod = 1000000007;

	static long add(long a, long b) {
		long r = a + b;
		if (r < 0) {
			r += mod;
		}
		return r % mod;
	}

	static long mul(long a, long b) {
		return (a * b) % mod;
	}

	static int gcd(int a, int b) {
		if (b == 0) {
			return a;
		} else {
			return gcd(b, a % b);
		}
	}

	static String str(List<Integer> a) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < a.size(); i++) {
			sb.append(a.get(i) + " ");
		}
		return sb.toString();
	}

	static String str(int[] a) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < a.length; i++) {
			sb.append(a[i] + " ");
		}
		return sb.toString();
	}

	static int[] getIntArr(Scanner in, int size) {
		int[] arr = new int[size];
		for (int i = 0; i < size; i++) {
			arr[i] = in.nextInt();
		}
		return arr;
	}

	static int[][] getIntArr(Scanner in, int row, int col) {
		int[][] arr = new int[row][];
		for (int i = 0; i < row; i++) {
			arr[i] = getIntArr(in, col);
		}
		return arr;
	}

	static long[] getLongArr(Scanner in, int size) {
		long[] arr = new long[size];
		for (int i = 0; i < size; i++) {
			arr[i] = in.nextLong();
		}
		return arr;
	}

	static long[][] getLongArr(Scanner in, int row, int col) {
		long[][] arr = new long[row][];
		for (int i = 0; i < row; i++) {
			arr[i] = getLongArr(in, col);
		}
		return arr;
	}

	static char[] getCharArr(Scanner in, int size) {
		char[] arr = in.next().toCharArray();
		return arr;
	}

	static char[][] getCharArr(Scanner in, int row, int col) {
		char[][] arr = new char[row][];
		for (int i = 0; i < row; i++) {
			arr[i] = getCharArr(in, col);
		}
		return arr;
	}

	static String[] getStringArr(Scanner in, int size) {
		String[] arr = new String[size];
		for (int i = 0; i < size; i++) {
			arr[i] = in.next();
		}
		return arr;
	}

	static void swap(int[] a, int i, int j) {
		int t = a[i];
		a[i] = a[j];
		a[j] = t;
	}

	static void set(int[][] a, int v) {
		for (int i = 0; i < a.length; i++) {
			for (int j = 0; j < a[i].length; j++) {
				a[i][j] = v;
			}
		}
	}

	static Map<Integer, List<Integer>> getEdges(Scanner in, int size, boolean directed) {
		Map<Integer, List<Integer>> edges = new HashMap<>();
		for (int i = 0; i < size; i++) {
			int from = in.nextInt();
			int to = in.nextInt();
			if (!edges.containsKey(from)) {
				edges.put(from, new ArrayList<Integer>());
			}
			edges.get(from).add(to);
			if (!directed) {
				if (!edges.containsKey(to)) {
					edges.put(to, new ArrayList<Integer>());
				}
				edges.get(to).add(from);
			}

		}
		return edges;
	}

}

**Instructions:**
- Focus on edge cases or scenarios that maximize the failure probability in faulty solutions.
- Due to the output length limit, you should generate a **small-scale** test input that is **complete and valid**.
- Output the test input directly, not code to generate it.

**Output format:**
```plaintext
{test input}
```

Think step by step.

Response:
To generate a challenging test input that exposes the bug in the given code, we need to consider the following:

1. **Edge Cases**: Test cases that push the boundaries of the input constraints.
2. **Special Configurations**: Configurations that might cause the algorithm to fail, such as complex cycles or specific patterns of directions.
3. **Small-Scale Input**: Ensure the input is small enough to be manageable but still challenging.

Let's break down the requirements and create a test case:

1. **Single Test Case**: Since the input format requires multiple test cases, we will start with a single test case.
2. **Small Grid**: Use a small grid to keep the input manageable.
3. **Unspecified Directions**: Include unspecified directions (`?`) to test the algorithm's ability to handle them optimally.
4. **Trap Configuration**: Create a configuration where it is possible to trap Rostam in a cycle or corner.

Given these points, let's create a test case:

### Test Case
```plaintext
1
3 3
???
???
???
```

### Explanation
- **Grid Size**: 3x3, which is small but still provides enough room for complex configurations.
- **All Unspecified Directions**: Using `?` for all cells ensures that the algorithm must determine the optimal direction for each cell to maximize the number of trapped cells.
- **Single Test Case**: Simplifies the input and focuses on the core logic of the algorithm.

This test case will challenge the algorithm to handle a completely unspecified grid and find the optimal configuration to maximize the number of trapped cells. The expected output for this test case is 9, as all cells can be configured to trap Rostam.


**Task:**
Generate a challenging test input that exposes the bug in the buggy code of the algorithm problem:
Algorithm Problem:
Title: Trapped in the Witch's Labyrinth
time_limit_ms: 3000
memory_limit_mb: 256
Description: In the fourth labor of Rostam, the legendary hero from the Shahnameh, an old witch has created a magical maze to trap him. The maze is a rectangular grid consisting of $$$n$$$ rows and $$$m$$$ columns. Each cell in the maze points in a specific direction: up, down, left, or right. The witch has enchanted Rostam so that whenever he is in a cell, he will move to the next cell in the direction indicated by that cell.

If Rostam eventually exits the maze, he will be freed from the witch's enchantment and will defeat her. However, if he remains trapped within the maze forever, he will never escape.

The witch has not yet determined the directions for all the cells. She wants to assign directions to the unspecified cells in such a way that the number of starting cells from which Rostam will be trapped forever is maximized. Your task is to find the maximum number of starting cells which make Rostam trapped.

Input: The first line of the input contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$), the number of test cases.

For each test case:

- The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 1000$$$), representing the number of rows and columns in the maze.
- Each of the next $$$n$$$ lines contains a string of $$$m$$$ characters representing the directions in the maze. Each character is one of the following:   U (up)  D (down)  L (left)  R (right)  ? (unspecified direction)

It's guaranteed that the sum of $$$n \cdot m$$$ over all test cases is at most $$$10^6$$$.

Output: For each test case, print a single integer, the maximum number of starting cells from which Rostam will be trapped forever after assigning directions to the unspecified cells optimally.

Examples:
input:
3
3 3
UUU
L?R
DDD
2 3
???
???
3 3
?U?
R?L
RDL
output:
0
6
5

Note: In the first test case, all of the cells will be good no matter what you do.

In the second test case, if you assign the ?s like the picture below, all of the cells will be bad:

In the third test case, if you assign the ?s like the picture below, you will have $$$5$$$ bad cells (red-shaded cells):

Buggy Code:
import java.util.*;
import java.lang.*;
import java.io.*;

public class Codechef
{
    public static class Pair{
        char a;
        int i, j;
        Pair(char a, int i, int j){
            this.a = a;
            this.i = i;
            this.j = j;
        }
    }
	public static void main (String[] args) throws java.lang.Exception
	{
		// your code goes here
		Scanner scn = new Scanner(System.in);
		int t = scn.nextInt();
		while(t-->0){
		    int n = scn.nextInt();
		    int m = scn.nextInt();
		    int q = 0;
		    Character arr[][] = new Character[n][m];
		    for(int i = 0; i < n; i++){
		        String s = scn.next();
		        for(int j = 0; j < m; j++){
		            arr[i][j] = s.charAt(j);
		            if(arr[i][j]=='?')q++;
		        }
		    }
		    if(q==n*m){
		        int ans = 0;
		        if(n==1&&m==1)ans = 0;
		        else ans = q;
		        System.out.println(ans);
		        continue;
		    }
		    int vis[][] = new int[n][m];
		    for(int i = 0; i < n; i++){
		        Arrays.fill(vis[i], 1);
		    }
		    Queue<Pair> pq = new LinkedList<>();
		    for(int i = 0; i < n; i++){
		        for(int j = 0; j < m; j++){
		            if(i==0&&j==0&&(arr[i][j]=='L'||arr[i][j]=='U'))pq.add(new Pair(arr[i][j], i, j));
		            else if(i==0&&j==m-1&&(arr[i][j]=='R'||arr[i][j]=='U'))pq.add(new Pair(arr[i][j], i, j));
		            else if(i==n-1&&j==0&&(arr[i][j]=='L'||arr[i][j]=='D'))pq.add(new Pair(arr[i][j], i, j));
		            else if(i==n-1&&j==m-1&&(arr[i][j]=='R'||arr[i][j]=='D'))pq.add(new Pair(arr[i][j], i, j));
		            else if(i==0&&j!=0&&arr[i][j]=='U')pq.add(new Pair(arr[i][j], i, j));
		            else if(j==0&&i!=0&&arr[i][j]=='L')pq.add(new Pair(arr[i][j], i, j));
		            else if(i==n-1&&j!=m-1&&arr[i][j]=='D')pq.add(new Pair(arr[i][j], i, j));
		            else if(j==m-1&&i!=n-1&&arr[i][j]=='R')pq.add(new Pair(arr[i][j], i, j));
		            else vis[i][j] = -1;
		        }
		    }
		    int ai[] = {-1,0,1,0};
		    int aj[] = {0,-1,0,-1};
		    while(pq.size()>0){
		        Pair rem = pq.remove();

		      //  System.out.print(rem.a+" "+rem.i+" "+rem.j+" next ");

		        vis[rem.i][rem.j] = 1;
		      //  for(int i = 0; i< 4; i++){
		      //      int ni = rem.i+ai[i];
		      //      int nj = rem.j+aj[i];
		      //      if(ni>=0&&ni<n&&nj>=0&&nj<m){
		      //          if(vis[ni][nj]==-1&&arr[ni][nj]!='?'){
		      //              pq.add(new Pair(arr[ni][nj], ni, nj));
		      //              vis[ni][nj] = 1;
		      //          }
		      //      }
		      //  }

		        if(rem.i-1>=0&&arr[rem.i-1][rem.j]=='D'&&vis[rem.i-1][rem.j]==-1){
		            vis[rem.i-1][rem.j]=1;
		          //  arr[rem.i-1][rem.j] = 'D';
		            pq.add(new Pair(arr[rem.i-1][rem.j], rem.i-1, rem.j));
		        } if(rem.i+1<n&&arr[rem.i+1][rem.j]=='U'&&vis[rem.i+1][rem.j]==-1){
		            vis[rem.i+1][rem.j]=1;
		          //  arr[rem.i+1][rem.j] = 'U';
		            pq.add(new Pair(arr[rem.i+1][rem.j], rem.i+1, rem.j));
		        } if(rem.j-1>=0&&arr[rem.i][rem.j-1]=='R'&&vis[rem.i][rem.j-1]==-1){
		            vis[rem.i][rem.j-1]=1;
		          //  arr[rem.i-1][rem.j] = 'R';
		            pq.add(new Pair(arr[rem.i][rem.j-1], rem.i, rem.j-1));
		        } if(rem.j+1<m&&arr[rem.i][rem.j+1]=='L'&&vis[rem.i][rem.j+1]==-1){
		            vis[rem.i][rem.j+1]=1;
		          //  arr[rem.i][rem.j+1] = 'L';
		            pq.add(new Pair(arr[rem.i][rem.j+1], rem.i, rem.j+1));
		        }
		    }
		  //  System.out.println();

		    for(int i = 0; i < n; i++){
		        for(int j = 0; j < m; j++){
		            if(vis[i][j]==-1&&arr[i][j]!='?'){
		                pq.add(new Pair(arr[i][j], i, j));
		            }
		        }
		    }

		    int count = 0;
		    while(pq.size()>0){
		        Pair rem = pq.remove();
		      //  System.out.print(rem.a+" "+rem.i+" "+rem.j+" next ");

		        vis[rem.i][rem.j] = 2;

		      //  vis[rem.i][rem.j] = 1;
		        if(rem.i-1>=0&&arr[rem.i-1][rem.j]=='?'){
		          //  vis[rem.i-1][rem.j]=2;
		            arr[rem.i-1][rem.j] = 'D';
		            pq.add(new Pair(arr[rem.i-1][rem.j], rem.i-1, rem.j));
		        } if(rem.i+1<n&&arr[rem.i+1][rem.j]=='?'){
		          //  vis[rem.i+1][rem.j]=2;
		            arr[rem.i+1][rem.j] = 'U';
		            pq.add(new Pair(arr[rem.i+1][rem.j], rem.i+1, rem.j));
		        } if(rem.j-1>=0&&arr[rem.i][rem.j-1]=='?'){
		          //  vis[rem.i][rem.j-1]=2;
		            arr[rem.i][rem.j-1] = 'R';
		            pq.add(new Pair(arr[rem.i][rem.j-1], rem.i, rem.j-1));
		        } if(rem.j+1<m&&arr[rem.i][rem.j+1]=='?'){
		          //  vis[rem.i][rem.j+1]=2;
		            arr[rem.i][rem.j+1] = 'L';
		            pq.add(new Pair(arr[rem.i][rem.j+1], rem.i, rem.j+1));
		        }
		    }

		    for(int i = 0; i < n; i++){
		        for(int j = 0; j < m; j++){
		            if(arr[i][j]=='?'){
		                if(i-1>=0&&(vis[i-1][j]==2||arr[i-1][j]=='?')){
		            vis[i][j]=2;
		          //  arr[rem.i-1][rem.j] = 'D';
		          //  pq.add(new Pair(arr[rem.i-1][rem.j], rem.i-1, rem.j));
		        } if(i+1<n&&(vis[i+1][j]==2||arr[i+1][j]=='?')){
		            vis[i+1][j]=2;
		          //  arr[rem.i+1][rem.j] = 'U';
		          //  pq.add(new Pair(arr[rem.i+1][rem.j], rem.i+1, rem.j));
		        } if(j-1>=0&&(vis[i][j-1]==2||arr[i][j-1]=='?')){
		            vis[i][j]=2;
		          //  arr[rem.i][rem.j-1] = 'R';
		          //  pq.add(new Pair(arr[rem.i][rem.j-1], rem.i, rem.j-1));
		        } if(j+1<m&&(vis[i][j+1]==2||arr[i][j+1]=='?')){
		            vis[i][j]=2;
		          //  arr[rem.i][rem.j+1] = 'L';
		          //  pq.add(new Pair(arr[rem.i][rem.j+1], rem.i, rem.j+1));
		        }
		            }
		        }
		    }
		  //  System.out.println();
		    for(int i = 0; i < n; i++){
		        for(int j = 0; j < m; j++){
		          //  System.out.print(arr[i][j]+""+vis[i][j]+" ");
		            if(vis[i][j]==2)count++;
		        }
		      //  System.out.println();
		    }
		    System.out.println(count);
		}

	}
}

**Instructions:**
- Focus on edge cases or scenarios that maximize the failure probability in faulty solutions.
- Due to the output length limit, you should generate a **small-scale** test input that is **complete and valid**.
- Output the test input directly, not code to generate it.

**Output format:**
```plaintext
{test input}
```

Think step by step.

Response:
```plaintext
3
3 3
UUU
L?R
DDD
2 3
???
???
3 3
?U?
R?L
RDL
```


**Task:**
Generate a challenging test input that exposes the bug in the buggy code of the algorithm problem:
Algorithm Problem:
Title: Trapped in the Witch's Labyrinth
time_limit_ms: 3000
memory_limit_mb: 256
Description: In the fourth labor of Rostam, the legendary hero from the Shahnameh, an old witch has created a magical maze to trap him. The maze is a rectangular grid consisting of $$$n$$$ rows and $$$m$$$ columns. Each cell in the maze points in a specific direction: up, down, left, or right. The witch has enchanted Rostam so that whenever he is in a cell, he will move to the next cell in the direction indicated by that cell.

If Rostam eventually exits the maze, he will be freed from the witch's enchantment and will defeat her. However, if he remains trapped within the maze forever, he will never escape.

The witch has not yet determined the directions for all the cells. She wants to assign directions to the unspecified cells in such a way that the number of starting cells from which Rostam will be trapped forever is maximized. Your task is to find the maximum number of starting cells which make Rostam trapped.

Input: The first line of the input contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$), the number of test cases.

For each test case:

- The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 1000$$$), representing the number of rows and columns in the maze.
- Each of the next $$$n$$$ lines contains a string of $$$m$$$ characters representing the directions in the maze. Each character is one of the following:   U (up)  D (down)  L (left)  R (right)  ? (unspecified direction)

It's guaranteed that the sum of $$$n \cdot m$$$ over all test cases is at most $$$10^6$$$.

Output: For each test case, print a single integer, the maximum number of starting cells from which Rostam will be trapped forever after assigning directions to the unspecified cells optimally.

Examples:
input:
3
3 3
UUU
L?R
DDD
2 3
???
???
3 3
?U?
R?L
RDL
output:
0
6
5

Note: In the first test case, all of the cells will be good no matter what you do.

In the second test case, if you assign the ?s like the picture below, all of the cells will be bad:

In the third test case, if you assign the ?s like the picture below, you will have $$$5$$$ bad cells (red-shaded cells):

Buggy Code:
#include<bits/stdc++.h>
using namespace std;
#define int long long
int a[1009][1009],b[1009][1009];
char c[1009][1009];
int ans;
int n,m;
int dfs(int x,int y){
	//cout<<x<<" "<<y<<"\n";
	if(x==0||y==0)return 0;
	if(x>n||y>m)return 0;
	if(b[x][y])return a[x][y];
	b[x][y]=1;
	if(c[x][y]=='U')if(dfs(x-1,y)){a[x][y]=1;}
	if(c[x][y]=='D')if(dfs(x+1,y)){a[x][y]=1;}
	if(c[x][y]=='R')if(dfs(x,y+1)){a[x][y]=1;}
	if(c[x][y]=='L')if(dfs(x,y-1)){a[x][y]=1;}
	return 0;
}
inline void solve(){
	cin>>n>>m;
	ans=0;
	for(int i=1;i<=n;i++)for(int j=1;j<=m;j++)cin>>c[i][j];
	for(int i=1;i<=n+1;i++)for(int j=1;j<=m+1;j++){
		a[i][j]=0;
		b[i][j]=0;
	}
	for(int i=1;i<=n+1;i++){
		for(int j=1;j<=m+1;j++){
			if(c[i][j]=='?'){
			  a[i][j]=2;
			  b[i][j]=1;
			  }
		}
	}
	for(int i=1;i<=n;i++){
		for(int j=1;j<=m;j++){
			if(b[i][j]==0)dfs(i,j);
		}
	}
	for(int i=1;i<=n;i++){
		for(int j=1;j<=m;j++){
			if(a[i][j]==2&&(a[i][j+1]||a[i][j-1]||a[i-1][j]||a[i+1][j]))ans++;
			else if(a[i][j]==1)ans++;
			//cout<<a[i][j]<<" ";
		}
		//cout<<"\n";
	}
	 cout<<ans<<"\n";
	return;
}
signed main(){
    int t1=1;
    cin>>t1;
    while(t1--)solve();
    return 0;
}

**Instructions:**
- Focus on edge cases or scenarios that maximize the failure probability in faulty solutions.
- Due to the output length limit, you should generate a **small-scale** test input that is **complete and valid**.
- Output the test input directly, not code to generate it.

**Output format:**
```plaintext
{test input}
```

Think step by step.

Response:
```plaintext
3
3 3
UUU
L?R
DDD
2 3
???
???
3 3
?U?
R?L
RDL
```


**Task:**
Generate a challenging test input that exposes the bug in the buggy code of the algorithm problem:
Algorithm Problem:
Title: Trapped in the Witch's Labyrinth
time_limit_ms: 3000
memory_limit_mb: 256
Description: In the fourth labor of Rostam, the legendary hero from the Shahnameh, an old witch has created a magical maze to trap him. The maze is a rectangular grid consisting of $$$n$$$ rows and $$$m$$$ columns. Each cell in the maze points in a specific direction: up, down, left, or right. The witch has enchanted Rostam so that whenever he is in a cell, he will move to the next cell in the direction indicated by that cell.

If Rostam eventually exits the maze, he will be freed from the witch's enchantment and will defeat her. However, if he remains trapped within the maze forever, he will never escape.

The witch has not yet determined the directions for all the cells. She wants to assign directions to the unspecified cells in such a way that the number of starting cells from which Rostam will be trapped forever is maximized. Your task is to find the maximum number of starting cells which make Rostam trapped.

Input: The first line of the input contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$), the number of test cases.

For each test case:

- The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 1000$$$), representing the number of rows and columns in the maze.
- Each of the next $$$n$$$ lines contains a string of $$$m$$$ characters representing the directions in the maze. Each character is one of the following:   U (up)  D (down)  L (left)  R (right)  ? (unspecified direction)

It's guaranteed that the sum of $$$n \cdot m$$$ over all test cases is at most $$$10^6$$$.

Output: For each test case, print a single integer, the maximum number of starting cells from which Rostam will be trapped forever after assigning directions to the unspecified cells optimally.

Examples:
input:
3
3 3
UUU
L?R
DDD
2 3
???
???
3 3
?U?
R?L
RDL
output:
0
6
5

Note: In the first test case, all of the cells will be good no matter what you do.

In the second test case, if you assign the ?s like the picture below, all of the cells will be bad:

In the third test case, if you assign the ?s like the picture below, you will have $$$5$$$ bad cells (red-shaded cells):

Buggy Code:
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

using namespace std;
using namespace __gnu_pbds;

int dx[] = {0, -1, 0, 1};
int dy[] = {-1, 0, 1, 0};

#define ll long long
#define ull unsigned long long
// #define debug(x) cout<<#x<<' '<<x<<endl;

template <typename A, typename B> ostream &operator<<(ostream &os, const pair<A, B> &p) { return os << '(' << p.first << ", " << p.second << ')'; }
template <typename T_container, typename T = typename enable_if<!is_same<T_container, string>::value, typename T_container::value_type>::type> ostream &operator<<(ostream &os, const T_container &v) { os << '{'; string sep; for (const T &x : v) os << sep << x, sep = ", "; return os << '}'; }
void dbg_out() { cerr << endl; }
template <typename Head, typename... Tail> void dbg_out(Head H, Tail... T) { cerr << " " << H; dbg_out(T...); }

#define debug(args...) cerr << "(" << #args << "):",dbg_out(args)

// #define int ll

#define mod 1000000007

# define INF 1e12
#define yes cout << "YES\n"
#define no cout << "NO\n"

#define all(v) v.begin(),v.end()

std::ostream&
operator<<( std::ostream& dest, __int128_t value )
{
    std::ostream::sentry s( dest );
    if ( s ) {
        __uint128_t tmp = value < 0 ? -value : value;
        char buffer[ 128 ];
        char* d = std::end( buffer );
        do
        {
            -- d;
            *d = "0123456789"[ tmp % 10 ];
            tmp /= 10;
        } while ( tmp != 0 );
        if ( value < 0 ) {
            -- d;
            *d = '-';
        }
        int len = std::end( buffer ) - d;
        if ( dest.rdbuf()->sputn( d, len ) != len ) {
            dest.setstate( std::ios_base::badbit );
        }
    }
    return dest;
}

/********************************GLOBAL DECLARE ******************/

/**************************************************************/

template <typename T>using orderedSet = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;

//find_by_order
//order_of_key

/******************************OTHER_FUNCTION***************************/

/******************************OTHER_FUNCTION END*********************************/

/**************************SOLVE_FUNCTION************************/

// const int sz=500200;

// int a[sz],t[4*sz],tmn[4*sz];

// void build(int l,int r,int idx){
//     if(l==r){
//         t[idx]=a[l];
//         return;
//     }
//     int mid=(l+r)/2;
//     build(l,mid,2*idx);
//     build(mid+1,r,2*idx+1);
//     t[idx]=max(t[2*idx],t[2*idx+1]);
// }

// int query(int l,int r,int idx,int lq,int rq){

//     if(l>=lq && r<=rq){
//         return t[idx];
//     }
//     if(r<lq || l>rq){
//         return 0;
//     }
//     int mid=(l+r)/2;
//     return max(query(l,mid,2*idx,lq,rq),query(mid+1,r,2*idx+1,lq,rq));
// }

void solve(int tc){

    int n,m;
    cin>>n>>m;
    vector<string> s(n);
    for(int i=0;i<n;i++){
        cin>>s[i];
    }

    for(int i=0;i<n;i++){
        for(int j=0;j<m;j++){
            if(s[i][j]=='?'){
                if(i-1>=0 && i-1<n){
                    if(s[i-1][j]=='?' || s[i-1][j]=='D'){
                        s[i][j]='U',s[i-1][j]='D';
                        continue;
                    }

                }
                if(j>0 && j+1<m){
                    if(s[i][j-1]=='?' || s[i][j-1]=='R'){
                        s[i][j]='L',s[i][j-1]='R';
                        continue;
                    }
                }
                if(i>=0 &&i<n-1){
                    if(s[i+1][j]=='?'|| s[i+1][j]=='U'){
                        s[i][j]='D',s[i+1][j]='U';
                        continue;
                    }
                }
                if(j>=0 &&j<m-1){
                    if(s[i][j+1]=='?'|| s[i][j+1]=='L'){
                        s[i][j]='R',s[i][j+1]='L';
                    }
                }
            }

        }
    }

    vector<vector<bool>> vis(n,vector<bool>(m,false));
    int cnt=0;

    auto dfs=[&](auto &&dfs,int i,int j)->void{
        if(!vis[i][j]){
            cnt++;
        }
        vis[i][j]=1;
        if(i>0 && i-1<n){
            if(!vis[i-1][j] && (s[i-1][j]=='D'|| s[i-1][j]=='?')){
                dfs(dfs,i-1,j);
            }

        }
        if(j>0 && j-1<m){
            if(!vis[i][j-1] && (s[i][j-1]=='R' ||s[i][j-1]=='?')){
                dfs(dfs,i,j-1);
            }
        }

        if(i>=0 && i+1<n){
            if(!vis[i+1][j] && (s[i+1][j]=='U'||s[i+1][j]=='?')){
                dfs(dfs,i+1,j);
            }
        }
        if(j>=0 && j+1<m){
            if(!vis[i][j+1] && (s[i][j+1]=='L' ||  s[i][j+1]=='?' )){
                dfs(dfs,i,j+1);
            }
        }

    };

    for(int i=0;i<n;i++){
        for(int j=0;j<m;j++){
            if(s[i][j]=='R'){
                if(j>=0 && j+1<m){
                    if(s[i][j+1]=='L'){
                        if(1){
                            // debug(i,j);
                            dfs(dfs,i,j);
                        }

                    }
                }
            }
            if(s[i][j]=='D'){
                if(i>=0 && i+1<n){
                    if(s[i+1][j]=='U'){
                        if(1){
                            dfs(dfs,i,j);
                        }
                    }
                }
            }
        }
    }

    cout<<cnt<<"\n";

}

/***************************SOLVE_FUNCTION END ***************************/

signed main()
{

    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int t=1;
    cin>>t;
    int cas=1;
    // cout<<cas;

    for(int i=1;i<=t;i++){
        // cout<<"Case "<<cas++<<":\n";
        solve(i);
    }

}

**Instructions:**
- Focus on edge cases or scenarios that maximize the failure probability in faulty solutions.
- Due to the output length limit, you should generate a **small-scale** test input that is **complete and valid**.
- Output the test input directly, not code to generate it.

**Output format:**
```plaintext
{test input}
```

Think step by step.

Response:
```plaintext
3
3 3
???
???
???
2 2
??
??
1 1
?
```


**Task:**
Generate a challenging test input that exposes the bug in the buggy code of the algorithm problem:
Algorithm Problem:
Title: Trapped in the Witch's Labyrinth
time_limit_ms: 3000
memory_limit_mb: 256
Description: In the fourth labor of Rostam, the legendary hero from the Shahnameh, an old witch has created a magical maze to trap him. The maze is a rectangular grid consisting of $$$n$$$ rows and $$$m$$$ columns. Each cell in the maze points in a specific direction: up, down, left, or right. The witch has enchanted Rostam so that whenever he is in a cell, he will move to the next cell in the direction indicated by that cell.

If Rostam eventually exits the maze, he will be freed from the witch's enchantment and will defeat her. However, if he remains trapped within the maze forever, he will never escape.

The witch has not yet determined the directions for all the cells. She wants to assign directions to the unspecified cells in such a way that the number of starting cells from which Rostam will be trapped forever is maximized. Your task is to find the maximum number of starting cells which make Rostam trapped.

Input: The first line of the input contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$), the number of test cases.

For each test case:

- The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 1000$$$), representing the number of rows and columns in the maze.
- Each of the next $$$n$$$ lines contains a string of $$$m$$$ characters representing the directions in the maze. Each character is one of the following:   U (up)  D (down)  L (left)  R (right)  ? (unspecified direction)

It's guaranteed that the sum of $$$n \cdot m$$$ over all test cases is at most $$$10^6$$$.

Output: For each test case, print a single integer, the maximum number of starting cells from which Rostam will be trapped forever after assigning directions to the unspecified cells optimally.

Examples:
input:
3
3 3
UUU
L?R
DDD
2 3
???
???
3 3
?U?
R?L
RDL
output:
0
6
5

Note: In the first test case, all of the cells will be good no matter what you do.

In the second test case, if you assign the ?s like the picture below, all of the cells will be bad:

In the third test case, if you assign the ?s like the picture below, you will have $$$5$$$ bad cells (red-shaded cells):

Buggy Code:
for test in range(int(input())):
    #bin_tree = Avl_tree()
    #n = int(input())
    n, m = map(int, input().split())
    a = []
    for i in range(n):
        a.append(str(input()))
    #s = str(input())
    #s = list(map(int, list(str(input()))))
    #r = list(map(int, list(str(input()))))
    #b = list(map(int, input().split()))
    #a = list(map(int, input().split()))
    #s = str(input())
    pos = [[0] * m for _ in range(n)]
    for i in range(n):
        for j in range(m):
            if a[i][j] != '?':
                if pos[i][j] == 0:
                    act = [i, j]
                    pam = []
                    while True:
                        pam.append(act.copy())
                        if a[act[0]][act[1]] == '?' or pos[act[0]][act[1]] == 1:
                            for x in pam:
                                pos[x[0]][x[1]] = 1
                            break
                        if pos[act[0]][act[1]] == 2:
                            for x in pam:
                                pos[x[0]][x[1]] = 2
                            break
                        if a[act[0]][act[1]] == 'D':
                            act[0] += 1
                            if act[0] >= n:
                                for x in pam:
                                    pos[x[0]][x[1]] = 2
                                break
                        elif a[act[0]][act[1]] == 'U':
                            act[0] -= 1
                            if act[0] < 0:
                                for x in pam:
                                    pos[x[0]][x[1]] = 2
                                break
                        elif a[act[0]][act[1]] == 'R':
                            act[1] += 1
                            if act[1] >= m:
                                for x in pam:
                                    pos[x[0]][x[1]] = 2
                                break
                        else:
                            act[1] -= 1
                            if act[1] < 0:
                                for x in pam:
                                    pos[x[0]][x[1]] = 2
                                break
    for i in range(n):
        for j in range(m):
            if a[i][j] == '?':
                vih = 2
                if i > 0:
                    if a[i - 1][j] == '?':
                        vih = 1
                    elif pos[i - 1][j] == 1:
                        vih = 1
                if j > 0:
                    if a[i][j - 1] == '?':
                        vih = 1
                    elif pos[i][j - 1] == 1:
                        vih = 1
                if i < n - 1:
                    if a[i + 1][j] == '?':
                        vih = 1
                    elif pos[i + 1][j] == 1:
                        vih = 1
                if j < m - 1:
                    if a[i][j + 1] == '?':
                        vih = 1
                    elif pos[i][j + 1] == 1:
                        vih = 1
                pos[i][j] = vih
    ans = 0
    for i in range(n):
        for j in range(m):
            if pos[i][j] == 1:
                ans += 1
    print(ans)
    # for x in pos:
    #     print(x)

**Instructions:**
- Focus on edge cases or scenarios that maximize the failure probability in faulty solutions.
- Due to the output length limit, you should generate a **small-scale** test input that is **complete and valid**.
- Output the test input directly, not code to generate it.

**Output format:**
```plaintext
{test input}
```

Think step by step.

Response:
```plaintext
1
3 3
?L?
?U?
?L?
```

**Explanation:**

This test case is designed to expose the bug in the buggy code by creating a scenario where the '?' cells can potentially form a cycle or lead to a cycle, but the code might not handle it correctly. Here's how it works:

1. The middle row has a 'U' which points up, and the cells above and below it are unspecified ('?').
2. The cells to the left and right of the 'U' are also unspecified ('?') and point left ('L').

The correct solution should consider that the unspecified cells can be assigned directions that create cycles, leading to the maximum number of trapped cells. However, the buggy code might not handle the cycle detection correctly, especially when it comes to setting the positions of the cells to either trapped (1) or escaped (2).

This input forces the code to handle the unspecified cells in a way that maximizes the number of trapped cells, which is 5 in this case. The correct output should be 5, but the buggy code might produce a different result due to its faulty logic in handling cycles and unspecified cells.


**Task:**
Generate a challenging test input that exposes the bug in the buggy code of the algorithm problem:
Algorithm Problem:
Title: Trapped in the Witch's Labyrinth
time_limit_ms: 3000
memory_limit_mb: 256
Description: In the fourth labor of Rostam, the legendary hero from the Shahnameh, an old witch has created a magical maze to trap him. The maze is a rectangular grid consisting of $$$n$$$ rows and $$$m$$$ columns. Each cell in the maze points in a specific direction: up, down, left, or right. The witch has enchanted Rostam so that whenever he is in a cell, he will move to the next cell in the direction indicated by that cell.

If Rostam eventually exits the maze, he will be freed from the witch's enchantment and will defeat her. However, if he remains trapped within the maze forever, he will never escape.

The witch has not yet determined the directions for all the cells. She wants to assign directions to the unspecified cells in such a way that the number of starting cells from which Rostam will be trapped forever is maximized. Your task is to find the maximum number of starting cells which make Rostam trapped.

Input: The first line of the input contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$), the number of test cases.

For each test case:

- The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 1000$$$), representing the number of rows and columns in the maze.
- Each of the next $$$n$$$ lines contains a string of $$$m$$$ characters representing the directions in the maze. Each character is one of the following:   U (up)  D (down)  L (left)  R (right)  ? (unspecified direction)

It's guaranteed that the sum of $$$n \cdot m$$$ over all test cases is at most $$$10^6$$$.

Output: For each test case, print a single integer, the maximum number of starting cells from which Rostam will be trapped forever after assigning directions to the unspecified cells optimally.

Examples:
input:
3
3 3
UUU
L?R
DDD
2 3
???
???
3 3
?U?
R?L
RDL
output:
0
6
5

Note: In the first test case, all of the cells will be good no matter what you do.

In the second test case, if you assign the ?s like the picture below, all of the cells will be bad:

In the third test case, if you assign the ?s like the picture below, you will have $$$5$$$ bad cells (red-shaded cells):

Buggy Code:

**Instructions:**
- Focus on edge cases or scenarios that maximize the failure probability in faulty solutions.
- Due to the output length limit, you should generate a **small-scale** test input that is **complete and valid**.
- Output the test input directly, not code to generate it.

**Output format:**
```plaintext
{test input}
```

Think step by step.

Response:
```plaintext
3
3 3
UUU
L?R
DDD
2 3
???
???
3 3
?U?
R?L
RDL
```


**Task:**
Generate a challenging test input that exposes the bug in the buggy code of the algorithm problem:
Algorithm Problem:
Title: Trapped in the Witch's Labyrinth
time_limit_ms: 3000
memory_limit_mb: 256
Description: In the fourth labor of Rostam, the legendary hero from the Shahnameh, an old witch has created a magical maze to trap him. The maze is a rectangular grid consisting of $$$n$$$ rows and $$$m$$$ columns. Each cell in the maze points in a specific direction: up, down, left, or right. The witch has enchanted Rostam so that whenever he is in a cell, he will move to the next cell in the direction indicated by that cell.

If Rostam eventually exits the maze, he will be freed from the witch's enchantment and will defeat her. However, if he remains trapped within the maze forever, he will never escape.

The witch has not yet determined the directions for all the cells. She wants to assign directions to the unspecified cells in such a way that the number of starting cells from which Rostam will be trapped forever is maximized. Your task is to find the maximum number of starting cells which make Rostam trapped.

Input: The first line of the input contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$), the number of test cases.

For each test case:

- The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 1000$$$), representing the number of rows and columns in the maze.
- Each of the next $$$n$$$ lines contains a string of $$$m$$$ characters representing the directions in the maze. Each character is one of the following:   U (up)  D (down)  L (left)  R (right)  ? (unspecified direction)

It's guaranteed that the sum of $$$n \cdot m$$$ over all test cases is at most $$$10^6$$$.

Output: For each test case, print a single integer, the maximum number of starting cells from which Rostam will be trapped forever after assigning directions to the unspecified cells optimally.

Examples:
input:
3
3 3
UUU
L?R
DDD
2 3
???
???
3 3
?U?
R?L
RDL
output:
0
6
5

Note: In the first test case, all of the cells will be good no matter what you do.

In the second test case, if you assign the ?s like the picture below, all of the cells will be bad:

In the third test case, if you assign the ?s like the picture below, you will have $$$5$$$ bad cells (red-shaded cells):

Buggy Code:
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;

public class Leetcode {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int t = sc.nextInt();

		while (t-- > 0) {
			solve(sc);
		}
	}

	private static void solve(Scanner sc) {
		int n = sc.nextInt();
		int m = sc.nextInt();
		sc.nextLine();
		String[] arr = new String[n];

		for (int i = 0; i < n; i++) {
			arr[i] = sc.nextLine();
		}

		int[][] dp = new int[n][m];

		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				dp[i][j] = -1;
			}
		}

		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				if (dp[i][j] == -1 && arr[i].charAt(j) != '?') {
					dfs(i, j, arr, dp);
				}
			}
		}

		int[][] directions = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
		int count = 0;

		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				if (dp[i][j] != -1) {
					count += dp[i][j];
				}
				else {
					for (int[] direction : directions) {
						int iNew = i + direction[0];
						int jNew = j + direction[1];

						if (iNew >= 0 && iNew < n && jNew >= 0 && jNew < m && Math.abs(dp[iNew][jNew]) == 1) {
							count++;
							break;
						}
					}
				}
			}
		}

		System.out.println(count);
	}

	private static int dfs(int i, int j, String[] arr, int[][] dp) {
		int n = arr.length;
		int m = arr[0].length();

		if (i < 0 || i >= n || j < 0 || j >= m) {
			return 0;
		}
		if (dp[i][j] != -1) {
			return dp[i][j];
		}

		if (arr[i].charAt(j) == 'U') {
			dp[i][j] = dfs(i - 1, j, arr, dp);
		}
		else if (arr[i].charAt(j) == 'D') {
			dp[i][j] = dfs(i + 1, j, arr, dp);
		}
		else if (arr[i].charAt(j) == 'L') {
			dp[i][j] = dfs(i, j - 1, arr, dp);
		}
		else if (arr[i].charAt(j) == 'R') {
			dp[i][j] = dfs(i, j + 1, arr, dp);
		}
		else {
			dp[i][j] = 1;
		}

		return dp[i][j];
	}
}

**Instructions:**
- Focus on edge cases or scenarios that maximize the failure probability in faulty solutions.
- Due to the output length limit, you should generate a **small-scale** test input that is **complete and valid**.
- Output the test input directly, not code to generate it.

**Output format:**
```plaintext
{test input}
```

Think step by step.

Response:
```plaintext
1
3 3
???
???
???
```


**Task:**
Generate a challenging test input that exposes the bug in the buggy code of the algorithm problem:
Algorithm Problem:
Title: Trapped in the Witch's Labyrinth
time_limit_ms: 3000
memory_limit_mb: 256
Description: In the fourth labor of Rostam, the legendary hero from the Shahnameh, an old witch has created a magical maze to trap him. The maze is a rectangular grid consisting of $$$n$$$ rows and $$$m$$$ columns. Each cell in the maze points in a specific direction: up, down, left, or right. The witch has enchanted Rostam so that whenever he is in a cell, he will move to the next cell in the direction indicated by that cell.

If Rostam eventually exits the maze, he will be freed from the witch's enchantment and will defeat her. However, if he remains trapped within the maze forever, he will never escape.

The witch has not yet determined the directions for all the cells. She wants to assign directions to the unspecified cells in such a way that the number of starting cells from which Rostam will be trapped forever is maximized. Your task is to find the maximum number of starting cells which make Rostam trapped.

Input: The first line of the input contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$), the number of test cases.

For each test case:

- The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 1000$$$), representing the number of rows and columns in the maze.
- Each of the next $$$n$$$ lines contains a string of $$$m$$$ characters representing the directions in the maze. Each character is one of the following:   U (up)  D (down)  L (left)  R (right)  ? (unspecified direction)

It's guaranteed that the sum of $$$n \cdot m$$$ over all test cases is at most $$$10^6$$$.

Output: For each test case, print a single integer, the maximum number of starting cells from which Rostam will be trapped forever after assigning directions to the unspecified cells optimally.

Examples:
input:
3
3 3
UUU
L?R
DDD
2 3
???
???
3 3
?U?
R?L
RDL
output:
0
6
5

Note: In the first test case, all of the cells will be good no matter what you do.

In the second test case, if you assign the ?s like the picture below, all of the cells will be bad:

In the third test case, if you assign the ?s like the picture below, you will have $$$5$$$ bad cells (red-shaded cells):

Buggy Code:
import java.io.*;
import java.util.*;
public class C {
	public static PrintWriter out;
//	static boolean good;
	static int n, m;
	static int dx[]= {-1, 1, 0, 0};
	static int dy[]= {0, 0, -1, 1};
	static char grid[][];
	public static void main(String[] args)throws IOException{
        JS sc=new JS();
        out=new PrintWriter(System.out);
        int t=sc.nextInt();
        outer: while(t-->0) {
        	n=sc.nextInt();
        	m=sc.nextInt();
        	int q=0;
        	grid=new char[n][m];
        	for(int i=0;i<n;i++) {
        		String s=sc.next();
        		for(int j=0;j<m;j++) {
        			grid[i][j]=s.charAt(j);
        			if(grid[i][j]!='?') {
        				q++;
        			}
        		}
        	}
        	if(q==0&&n==1&&m==1){
        		out.println(0);
        		continue outer;
        	}else if(q==0) {
        		out.println(n*m);
        		continue outer;
        	}
        	boolean vis[][]=new boolean[n][m];
        	boolean good[][]=new boolean[n][m];
        	for(int i=0;i<n;i++) {
        		Arrays.fill(good[i], false);
        	}
        	for(int i=0;i<n;i++) {
        		for(int j=0;j<m;j++) {
        			if(grid[i][j]!='?'&&!vis[i][j]) {
        				dfs(i, j, vis, good);
        			}
        		}
        	}
        	int ans=0;
        	for(int i=0;i<n;i++) {
        		for(int j=0;j<m;j++) {
        			if(good[i][j]&&grid[i][j]!='?') {
            			ans++;
            		}else if(grid[i][j]=='?') {
            			boolean has=false;
            			for(int c=0;c<4;c++) {
            				int nextX=dx[c]+i;
            				int nextY=dy[c]+j;
            				if(check(nextX, nextY)&&(good[nextX][nextY]||grid[nextX][nextY]=='?')) {
            					has=true;
            				}
            			}
            			if(has) {
            				ans++;
            			}
            		}
        		}
        	}
        	out.println(ans);
        }
        out.close();
	}
	static void dfs(int curx, int cury, boolean vis[][], boolean good[][]) {
		vis[curx][cury]=true;
		int nextX=0;
		int nextY=0;
		if(grid[curx][cury]=='U') {
			nextX=curx-1;
			nextY=cury;
		}else if(grid[curx][cury]=='D') {
			nextX=curx+1;
			nextY=cury;
		}else if(grid[curx][cury]=='L') {
			nextX=curx;
			nextY=cury-1;
		}else if(grid[curx][cury]=='R') {
			nextX=curx;
			nextY=cury+1;
		}
		if(!check(nextX, nextY)) {
			good[curx][cury]=false;
		}else {
			if(grid[nextX][nextY]!='?') {
				dfs(nextX, nextY, vis, good);
			}else {
				good[nextX][nextY]=true;
				vis[nextX][nextY]=true;
			}
			if(vis[nextX][nextY]&&good[nextX][nextY]) {
				good[curx][cury]=true;
			}else if(vis[nextX][nextY]&&!good[nextX][nextY]) {
				good[curx][cury]=false;
			}else if(grid[nextX][nextY]=='?') {
				good[curx][cury]=true;
			}
		}
	}
	static boolean check(int x, int y) {
		return x>=0&&y>=0&&x<n&&y<m;
	}
	static class Pair implements Comparable<Pair>{
		long x;
		int y;
		public Pair(long x, int y) {
			this.x=x;this.y=y;
		}
		public int compareTo(Pair p) {
			return Long.compare(x, p.x);
		}
	}
	static class Triple{
		int a, b, c;
		public Triple(int a, int b, int c) {
			this.a=a;this.b=b;this.c=c;
		}
	}
	public static long power(long a, long b, int mod) {
		long res=1;
		while(b!=0) {
			if(b%2==1) {
				res=(res*a)%mod;
			}
			a=(a*a)%mod;
			b/=2;
		}
		return res;
	}
	static class JS {
	    public int BS = 1<<16;
	    public char NC = (char)0;
	    byte[] buf = new byte[BS];
	    int bId = 0, size = 0;
	    char c = NC;
	    double num = 1;
	    BufferedInputStream in;

	    public JS() {
	        in = new BufferedInputStream(System.in, BS);
	    }

	    public JS(String s) throws FileNotFoundException {
	        in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
	    }

	    public char nextChar(){
	        while(bId==size) {
	            try {
	                size = in.read(buf);
	            }catch(Exception e) {
	                return NC;
	            }
	            if(size==-1)return NC;
	            bId=0;
	        }
	        return (char)buf[bId++];
	    }

	    public int nextInt() {
	        return (int)nextLong();
	    }

	    public long nextLong() {
	        num=1;
	        boolean neg = false;
	        if(c==NC)c=nextChar();
	        for(;(c<'0' || c>'9'); c = nextChar()) {
	            if(c=='-')neg=true;
	        }
	        long res = 0;
	        for(; c>='0' && c <='9'; c=nextChar()) {
	            res = (res<<3)+(res<<1)+c-'0';
	            num*=10;
	        }
	        return neg?-res:res;
	    }

	    public double nextDouble() {
	        double cur = nextLong();
	        return c!='.' ? cur:cur+nextLong()/num;
	    }

	    public String next() {
	        StringBuilder res = new StringBuilder();
	        while(c<=32)c=nextChar();
	        while(c>32) {
	            res.append(c);
	            c=nextChar();
	        }
	        return res.toString();
	    }

	    public String nextLine() {
	        StringBuilder res = new StringBuilder();
	        while(c<=32)c=nextChar();
	        while(c!='\n') {
	            res.append(c);
	            c=nextChar();
	        }
	        return res.toString();
	    }

	    public boolean hasNext() {
	        if(c>32)return true;
	        while(true) {
	            c=nextChar();
	            if(c==NC)return false;
	            else if(c>32)return true;
	        }
	    }
	}
}

**Instructions:**
- Focus on edge cases or scenarios that maximize the failure probability in faulty solutions.
- Due to the output length limit, you should generate a **small-scale** test input that is **complete and valid**.
- Output the test input directly, not code to generate it.

**Output format:**
```plaintext
{test input}
```

Think step by step.

Response:
To create a challenging test input that exposes the bug in the provided buggy code, we need to focus on edge cases or scenarios that are likely to cause issues. The bug in the code might be related to how it handles unspecified directions (denoted by `?`) and how it determines if a cell will trap Rostam forever.

### Step-by-Step Analysis:
1. **Single Cell Maze:**
   - If the maze is a single cell, the code should handle it correctly. However, this is already covered in the example provided.

2. **Maze with All Unspecified Directions:**
   - If all cells are unspecified, the code should output the total number of cells, as any direction can be assigned to make Rostam trapped. This is also covered in the example.

3. **Maze with Mixed Specified and Unspecified Directions:**
   - This is where the bug is more likely to be exposed. We need to create a scenario where the code's logic for determining trapped cells might fail.

4. **Edge Cases:**
   - **Single Row or Single Column Maze:**
     - These can be tricky because the movement in one direction might be limited.
   - **Maze with a Loop:**
     - If there is a loop in the specified directions, the code might not handle it correctly.
   - **Maze with a Path to the Edge:**
     - If there is a path that leads directly to the edge, the code should correctly identify that Rostam can escape.

### Challenging Test Input:
Let's create a maze with a single row and mixed specified and unspecified directions. This will test how the code handles a linear path and the unspecified directions.

```plaintext
1
1 5
U?R?L
```

### Explanation:
- **1 5**: This indicates a single row with 5 columns.
- **U?R?L**: The directions are `U` (up), `?` (unspecified), `R` (right), `?` (unspecified), and `L` (left).

### Expected Output:
- The expected output for this input is `3`.
  - The cells at positions (0, 1), (0, 3), and (0, 4) can be made to trap Rostam forever by assigning appropriate directions to the unspecified cells.

This input is designed to challenge the code's ability to correctly handle a linear path and the unspecified directions, potentially exposing any bugs in the logic for determining trapped cells.


**Task:**
Generate a challenging test input that exposes the bug in the buggy code of the algorithm problem:
Algorithm Problem:
Title: Trapped in the Witch's Labyrinth
time_limit_ms: 3000
memory_limit_mb: 256
Description: In the fourth labor of Rostam, the legendary hero from the Shahnameh, an old witch has created a magical maze to trap him. The maze is a rectangular grid consisting of $$$n$$$ rows and $$$m$$$ columns. Each cell in the maze points in a specific direction: up, down, left, or right. The witch has enchanted Rostam so that whenever he is in a cell, he will move to the next cell in the direction indicated by that cell.

If Rostam eventually exits the maze, he will be freed from the witch's enchantment and will defeat her. However, if he remains trapped within the maze forever, he will never escape.

The witch has not yet determined the directions for all the cells. She wants to assign directions to the unspecified cells in such a way that the number of starting cells from which Rostam will be trapped forever is maximized. Your task is to find the maximum number of starting cells which make Rostam trapped.

Input: The first line of the input contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$), the number of test cases.

For each test case:

- The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 1000$$$), representing the number of rows and columns in the maze.
- Each of the next $$$n$$$ lines contains a string of $$$m$$$ characters representing the directions in the maze. Each character is one of the following:   U (up)  D (down)  L (left)  R (right)  ? (unspecified direction)

It's guaranteed that the sum of $$$n \cdot m$$$ over all test cases is at most $$$10^6$$$.

Output: For each test case, print a single integer, the maximum number of starting cells from which Rostam will be trapped forever after assigning directions to the unspecified cells optimally.

Examples:
input:
3
3 3
UUU
L?R
DDD
2 3
???
???
3 3
?U?
R?L
RDL
output:
0
6
5

Note: In the first test case, all of the cells will be good no matter what you do.

In the second test case, if you assign the ?s like the picture below, all of the cells will be bad:

In the third test case, if you assign the ?s like the picture below, you will have $$$5$$$ bad cells (red-shaded cells):

Buggy Code:
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define take(n) \
    ll n;       \
    cin >> n;
#define takearr(arr, n)        \
    ll arr[n];                 \
    for (ll i = 0; i < n; i++) \
        cin >> arr[i];
// rep(i, 0, n-1){}; loop from 0 to n-1
#define vl vector<ll>
#define takevec(v, n)          \
    vector<ll> v;              \
    for (ll i = 0; i < n; i++) \
    {                          \
        ll x;                  \
        cin >> x;              \
        v.push_back(x);        \
    }
#define vpl vector<pair<ll, ll>>
#define takevp(v, n)           \
    vector<pair<ll, ll>> vp;   \
    for (ll i = 0; i < n; i++) \
    {                          \
        ll x, y;               \
        cin >> x >> y;         \
        v.push_back({x, y});   \
    }
#define printarr(a, n)         \
    for (ll i = 0; i < n-1; i++) \
        cout << a[i] << " ";   \
        cout << a[n-1];          \
    cout << '\n';
#define printy cout << "YES" << '\n';
#define printn cout << "NO" << '\n';
#ifndef ONLINE_JUDGE
#define check cout << "rechead here" << '\n';
#define checkval(v) cout << #v << " = " << v << '\n';
#define checkvec(v) forf(i, 0, v.size()) cout << v[i] << " ";
#define checkvp(vp) forf(i, 0, vp.size()) cout << vp[i].first << " " << vp[i].second << '\n';
#else
#define check
#define checkval(v, s)
#define checkvec(v)
#define printvp(vp)
#endif
#define printans cout << ans << '\n';
#define forf(i, a, b) for (long long i = a; i < b; i++)
#define forb(i, s, e) for (long long i = s; i >= e; i--)
#define printv(v) forf(i, 0, v.size()) cout << v[i] << " ";
#define printvp(vp) forf(i, 0, vp.size()) cout << vp[i].first << " " << vp[i].second << '\n';
#define endl '\n'
#define ff first
#define ss second

void solve(){
    take(n) take(m)
    string s[n];
    for (ll i = 0; i < n; i++)
    {
        cin>>s[i];
    }
    ll ans=0;
    vector<vector<bool>> checked(n,vector<bool>(m,false)),trap(n,vector<bool>(m,false));
    for (ll i = 0; i < n; i++)
    {
        for (ll j = 0; j < m; j++)
        {
            // if(i==0 && j==3){
            //     for (ll x = 0; x < n; x++)
            //     {
            //         for (ll y = 0; y < m; y++)
            //         {
            //             cout<<trap[x][y]<<" ";
            //         }
            //         cout<<endl;
            //     }

            //     return;
            // }
            if(checked[i][j]) continue;
            if(s[i][j]=='?') continue;
            ll x=i,y=j;
            stack<pair<ll,ll>> st;
            vector<vector<bool>> vis(n,vector<bool>(m,false));
            while(1){
                if(vis[x][y]){
                    while(!st.empty()){
                        checked[st.top().first][st.top().second]=true;
                        trap[st.top().first][st.top().second]=true;
                        st.pop();
                    }
                    break;
                }
                st.push({x,y});
                vis[x][y]=true;
                if(s[x][y]=='L'){
                    if(y-1<0){
                        while(!st.empty()){
                            checked[st.top().first][st.top().second]=true;
                            st.pop();
                        }
                        break;
                    }else if(s[x][y-1]=='?'){
                        s[x][y-1]='R';
                        st.push({x,y-1});
                        vis[x][y-1]=true;
                        while(!st.empty()){
                            checked[st.top().first][st.top().second]=true;
                            trap[st.top().first][st.top().second]=true;
                            st.pop();
                        }
                        break;
                    }else if(trap[x][y-1]){
                        while(!st.empty()){
                            checked[st.top().first][st.top().second]=true;
                            trap[st.top().first][st.top().second]=true;
                            st.pop();
                        }
                        break;
                    }else if(checked[x][y-1]){
                        while(!st.empty()){
                            checked[st.top().first][st.top().second]=true;
                            st.pop();
                        }
                        break;
                    }else{
                        y--;
                    }
                }else if(s[x][y]=='R'){
                    if(y+1>=m){
                        while(!st.empty()){
                            checked[st.top().first][st.top().second]=true;
                            st.pop();
                        }
                        break;
                    }else if(s[x][y+1]=='?'){
                        s[x][y+1]='L';
                        st.push({x,y+1});
                        vis[x][y+1]=true;
                        while(!st.empty()){
                            checked[st.top().first][st.top().second]=true;
                            trap[st.top().first][st.top().second]=true;
                            st.pop();
                        }
                        break;
                    }else if(trap[x][y+1]){
                        while(!st.empty()){
                            checked[st.top().first][st.top().second]=true;
                            trap[st.top().first][st.top().second]=true;
                            st.pop();
                        }
                        break;
                    }else if(checked[x][y+1]){
                        while(!st.empty()){
                            checked[st.top().first][st.top().second]=true;
                            st.pop();
                        }
                        break;
                    }else{
                        y++;
                    }
                }else if(s[x][y]=='U'){
                    if(x-1<0){
                        while(!st.empty()){
                            checked[st.top().first][st.top().second]=true;
                            st.pop();
                        }
                        break;
                    }else if(s[x-1][y]=='?'){
                        s[x-1][y]='D';
                        st.push({x-1,y});
                        vis[x-1][y]=true;
                        while(!st.empty()){
                            checked[st.top().first][st.top().second]=true;
                            trap[st.top().first][st.top().second]=true;
                            st.pop();
                        }
                        break;
                    }else if(trap[x-1][y]){
                        while(!st.empty()){
                            checked[st.top().first][st.top().second]=true;
                            trap[st.top().first][st.top().second]=true;
                            st.pop();
                        }
                        break;
                    }else if(checked[x-1][y]){
                        while(!st.empty()){
                            checked[st.top().first][st.top().second]=true;
                            st.pop();
                        }
                        break;
                    }else{
                        x--;
                    }
                }else if(s[x][y]=='D'){
                    if(x+1>=n){
                        while(!st.empty()){
                            checked[st.top().first][st.top().second]=true;
                            st.pop();
                        }
                        break;
                    }else if(s[x+1][y]=='?'){
                        s[x+1][y]='U';
                        st.push({x+1,y});
                        vis[x+1][y]=true;
                        while(!st.empty()){
                            checked[st.top().first][st.top().second]=true;
                            trap[st.top().first][st.top().second]=true;
                            st.pop();
                        }
                        break;
                    }else if(trap[x+1][y]){
                        while(!st.empty()){
                            checked[st.top().first][st.top().second]=true;
                            trap[st.top().first][st.top().second]=true;
                            st.pop();
                        }
                        break;
                    }else if(checked[x+1][y]){
                        while(!st.empty()){
                            checked[st.top().first][st.top().second]=true;
                            st.pop();
                        }
                        break;
                    }else{
                        x++;
                    }
                }
            }
        }
    }

    for (ll i = 0; i < n; i++)
    {
        for (ll j = 0; j < m; j++)
        {
            if(s[i][j]=='?'){
                if(i-1>=0){
                    if(trap[i-1][j]){
                        s[i][j]='U';
                        trap[i][j]=true;
                    }else if(s[i-1][j]=='?'){
                        s[i][j]='U';
                        s[i-1][j]='D';
                        trap[i][j]=true;
                        trap[i-1][j]=true;
                    }
                }
                if(i+1<n && !trap[i][j]){
                    if(trap[i+1][j]){
                        s[i][j]='D';
                        trap[i][j]=true;
                    }else if(s[i+1][j]=='?'){
                        s[i][j]='D';
                        s[i+1][j]='U';
                        trap[i][j]=true;
                        trap[i+1][j]=true;
                    }
                }
                if(j-1>=0 && !trap[i][j]){
                    if(trap[i][j-1]){
                        s[i][j]='L';
                        trap[i][j]=true;
                    }else if(s[i][j-1]=='?'){
                        s[i][j]='L';
                        s[i][j-1]='R';
                        trap[i][j]=true;
                        trap[i][j-1]=true;
                    }
                }
                if(j+1<m && !trap[i][j]){
                    if(trap[i][j+1]){
                        s[i][j]='R';
                        trap[i][j]=true;
                    }else if(s[i][j+1]=='?'){
                        s[i][j]='R';
                        s[i][j+1]='L';
                        trap[i][j]=true;
                        trap[i][j+1]=true;
                    }
                }
            }
        }
    }
    for(ll i=0;i<n;i++){
        for(ll j=0;j<m;j++){
            if(trap[i][j]) ans++;
            // cout<<trap[i][j]<<" ";
        }
        // cout<<endl;
    }
    printans
}

int main()
{
    #ifndef ONLINE_JUDGE
    freopen("Error.txt", "w", stderr);
    #endif
    ios_base::sync_with_stdio(false);       // these are useful for
    cin.tie(0); cout.tie(0);                // for large inputs  (>=10^6 types)
    int t;  cin >> t;   while (t--)
    solve();
    return 0;
}

**Instructions:**
- Focus on edge cases or scenarios that maximize the failure probability in faulty solutions.
- Due to the output length limit, you should generate a **small-scale** test input that is **complete and valid**.
- Output the test input directly, not code to generate it.

**Output format:**
```plaintext
{test input}
```

Think step by step.

Response:
To generate a challenging test input that exposes the bug in the provided buggy code, let's consider the following:

1. **Edge Cases**:
   - **Single Cell Maze**: A maze with a single cell can help verify how the code handles the simplest case.
   - **All Unspecified Cells**: A maze with all cells unspecified can test how the code handles the maximum flexibility in direction assignments.
   - **Cycle Formation**: A maze that can form a cycle with unspecified cells can test the logic for trapping Rostam.

2. **Specific Scenarios**:
   - **Unspecified Cells on Edges**: Test how the code handles unspecified cells on the edges of the maze.
   - **Unspecified Cells in the Middle**: Test how the code handles unspecified cells in the middle of the maze.
   - **Complex Pathing**: Test how the code handles complex pathing with a mix of specified and unspecified cells.

Let's create a small-scale test input that covers these aspects:

```plaintext
3
1 1
?
2 2
??
??
3 3
?U?
R?L
RDL
```

### Explanation:
1. **Single Cell Maze**:
   - **Input**: `1 1` followed by `?`
   - **Expected Output**: `1` (The only cell is unspecified, and it can be assigned any direction, but it will always be trapped since there are no other cells to move to.)

2. **All Unspecified Cells**:
   - **Input**: `2 2` followed by `??` and `??`
   - **Expected Output**: `4` (All cells are unspecified, and they can be assigned directions to form a cycle, trapping Rostam.)

3. **Complex Pathing**:
   - **Input**: `3 3` followed by `?U?`, `R?L`, `RDL`
   - **Expected Output**: `5` (This maze has a mix of specified and unspecified cells. The unspecified cells can be assigned directions to maximize the number of trapped cells.)

This test input should help expose any issues in the buggy code by covering a variety of edge cases and complex scenarios.


**Task:**
Generate a challenging test input that exposes the bug in the buggy code of the algorithm problem:
Algorithm Problem:
Title: Trapped in the Witch's Labyrinth
time_limit_ms: 3000
memory_limit_mb: 256
Description: In the fourth labor of Rostam, the legendary hero from the Shahnameh, an old witch has created a magical maze to trap him. The maze is a rectangular grid consisting of $$$n$$$ rows and $$$m$$$ columns. Each cell in the maze points in a specific direction: up, down, left, or right. The witch has enchanted Rostam so that whenever he is in a cell, he will move to the next cell in the direction indicated by that cell.

If Rostam eventually exits the maze, he will be freed from the witch's enchantment and will defeat her. However, if he remains trapped within the maze forever, he will never escape.

The witch has not yet determined the directions for all the cells. She wants to assign directions to the unspecified cells in such a way that the number of starting cells from which Rostam will be trapped forever is maximized. Your task is to find the maximum number of starting cells which make Rostam trapped.

Input: The first line of the input contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$), the number of test cases.

For each test case:

- The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 1000$$$), representing the number of rows and columns in the maze.
- Each of the next $$$n$$$ lines contains a string of $$$m$$$ characters representing the directions in the maze. Each character is one of the following:   U (up)  D (down)  L (left)  R (right)  ? (unspecified direction)

It's guaranteed that the sum of $$$n \cdot m$$$ over all test cases is at most $$$10^6$$$.

Output: For each test case, print a single integer, the maximum number of starting cells from which Rostam will be trapped forever after assigning directions to the unspecified cells optimally.

Examples:
input:
3
3 3
UUU
L?R
DDD
2 3
???
???
3 3
?U?
R?L
RDL
output:
0
6
5

Note: In the first test case, all of the cells will be good no matter what you do.

In the second test case, if you assign the ?s like the picture below, all of the cells will be bad:

In the third test case, if you assign the ?s like the picture below, you will have $$$5$$$ bad cells (red-shaded cells):

Buggy Code:
def dfs(grid, visited, trapped, x, y, n, m):
    if visited[x][y]:
        return True  # Cycle detected
    if trapped[x][y] != -1:
        return trapped[x][y]

    visited[x][y] = True
    trapped[x][y] = False

    directions = {'U': (-1, 0), 'D': (1, 0), 'L': (0, -1), 'R': (0, 1)}

    for direction in directions:
        nx, ny = x + directions[direction][0], y + directions[direction][1]
        if 0 <= nx < n and 0 <= ny < m:
            if grid[x][y] == '?' or grid[x][y] == direction:
                if dfs(grid, visited, trapped, nx, ny, n, m):
                    trapped[x][y] = True
                    break

    visited[x][y] = False
    return trapped[x][y]

def max_trapped_cells(t, cases):
    results = []
    for n, m, grid in cases:
        trapped = [[-1 for _ in range(m)] for _ in range(n)]
        for i in range(n):
            for j in range(m):
                if trapped[i][j] == -1:
                    visited = [[False for _ in range(m)] for _ in range(n)]
                    dfs(grid, visited, trapped, i, j, n, m)

        result = sum(sum(row) for row in trapped)
        results.append(result)

    return results

# Read input
import sys
input = sys.stdin.read
data = input().split()

t = int(data[0])
cases = []
index = 1
for _ in range(t):
    n, m = int(data[index]), int(data[index + 1])
    index += 2
    grid = [list(data[index + i]) for i in range(n)]
    index += n
    cases.append((n, m, grid))

# Solve the problem
results = max_trapped_cells(t, cases)

# Print results
for result in results:
    print(result)

# pZE1GwsqATe8Igd9vWP

**Instructions:**
- Focus on edge cases or scenarios that maximize the failure probability in faulty solutions.
- Due to the output length limit, you should generate a **small-scale** test input that is **complete and valid**.
- Output the test input directly, not code to generate it.

**Output format:**
```plaintext
{test input}
```

Think step by step.

Response:
To generate a challenging test input that exposes the bug in the given code, we need to focus on scenarios where the algorithm might fail to correctly detect cycles or handle unspecified directions. Here are the steps to create such a test input:

1. **Edge Cases with Cycles:**
   - Create a grid where there are multiple cycles, and some cells are unspecified. This can help test how the algorithm handles cycles and whether it correctly identifies trapped cells.

2. **Unspecified Directions:**
   - Include grids with a significant number of unspecified directions to see if the algorithm can handle the complexity of assigning directions optimally.

3. **Small-Scale Test Case:**
   - Since we need a small-scale test case, we can use a 3x3 grid or a 4x4 grid to ensure it is manageable and complete.

Let's create a 3x3 grid with a cycle and some unspecified directions:

```plaintext
1
3 3
R?L
?U?
L?R
```

Explanation:
- The grid has a cycle in the middle (R?L, ?U?, L?R) with some unspecified directions.
- This setup will test the algorithm's ability to handle cycles and correctly assign directions to the unspecified cells to maximize trapped cells.

Here is the test input:

```plaintext
1
3 3
R?L
?U?
L?R
```


**Task:**
Generate a challenging test input that exposes the bug in the buggy code of the algorithm problem:
Algorithm Problem:
Title: Trapped in the Witch's Labyrinth
time_limit_ms: 3000
memory_limit_mb: 256
Description: In the fourth labor of Rostam, the legendary hero from the Shahnameh, an old witch has created a magical maze to trap him. The maze is a rectangular grid consisting of $$$n$$$ rows and $$$m$$$ columns. Each cell in the maze points in a specific direction: up, down, left, or right. The witch has enchanted Rostam so that whenever he is in a cell, he will move to the next cell in the direction indicated by that cell.

If Rostam eventually exits the maze, he will be freed from the witch's enchantment and will defeat her. However, if he remains trapped within the maze forever, he will never escape.

The witch has not yet determined the directions for all the cells. She wants to assign directions to the unspecified cells in such a way that the number of starting cells from which Rostam will be trapped forever is maximized. Your task is to find the maximum number of starting cells which make Rostam trapped.

Input: The first line of the input contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$), the number of test cases.

For each test case:

- The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 1000$$$), representing the number of rows and columns in the maze.
- Each of the next $$$n$$$ lines contains a string of $$$m$$$ characters representing the directions in the maze. Each character is one of the following:   U (up)  D (down)  L (left)  R (right)  ? (unspecified direction)

It's guaranteed that the sum of $$$n \cdot m$$$ over all test cases is at most $$$10^6$$$.

Output: For each test case, print a single integer, the maximum number of starting cells from which Rostam will be trapped forever after assigning directions to the unspecified cells optimally.

Examples:
input:
3
3 3
UUU
L?R
DDD
2 3
???
???
3 3
?U?
R?L
RDL
output:
0
6
5

Note: In the first test case, all of the cells will be good no matter what you do.

In the second test case, if you assign the ?s like the picture below, all of the cells will be bad:

In the third test case, if you assign the ?s like the picture below, you will have $$$5$$$ bad cells (red-shaded cells):

Buggy Code:
t = int(input())
for _ in range(t):
    n, m = map(int, input().split())
    grid = [list(input()) for _ in range(n)]
    dir_map = {'U': (-1, 0), 'D': (1, 0), 'L': (0, -1), 'R': (0, 1)}
    reverse_graph = {}
    escape_cells = set()
    specified_cells = set()

    for i in range(n):
        for j in range(m):
            if grid[i][j] != '?':
                specified_cells.add((i, j))
                di, dj = dir_map[grid[i][j]]
                ni, nj = i + di, j + dj
                if 0 <= ni < n and 0 <= nj < m:
                    reverse_graph.setdefault((ni, nj), []).append((i, j))
                else:
                    escape_cells.add((i, j))

    from collections import deque
    visited = set(escape_cells)
    queue = deque(escape_cells)
    while queue:
        i, j = queue.popleft()
        for pi, pj in reverse_graph.get((i, j), []):
            if (pi, pj) not in visited:
                visited.add((pi, pj))
                queue.append((pi, pj))

    trapped_specified = specified_cells - visited

    trapped_unspecified = 0
    for i in range(n):
        for j in range(m):
            if grid[i][j] == '?':
                has_non_escape_neighbor = False
                for di, dj in dir_map.values():
                    ni, nj = i + di, j + dj
                    if 0 <= ni < n and 0 <= nj < m:
                        if (ni, nj) not in visited:
                            has_non_escape_neighbor = True
                            break
                if has_non_escape_neighbor:
                    trapped_unspecified += 1

    max_trapped = len(trapped_specified) + trapped_unspecified
    print(max_trapped)

**Instructions:**
- Focus on edge cases or scenarios that maximize the failure probability in faulty solutions.
- Due to the output length limit, you should generate a **small-scale** test input that is **complete and valid**.
- Output the test input directly, not code to generate it.

**Output format:**
```plaintext
{test input}
```

Think step by step.

Response:
```plaintext
1
3 3
???
???
???
```


**Task:**
Generate a challenging test input that exposes the bug in the buggy code of the algorithm problem:
Algorithm Problem:
Title: Trapped in the Witch's Labyrinth
time_limit_ms: 3000
memory_limit_mb: 256
Description: In the fourth labor of Rostam, the legendary hero from the Shahnameh, an old witch has created a magical maze to trap him. The maze is a rectangular grid consisting of $$$n$$$ rows and $$$m$$$ columns. Each cell in the maze points in a specific direction: up, down, left, or right. The witch has enchanted Rostam so that whenever he is in a cell, he will move to the next cell in the direction indicated by that cell.

If Rostam eventually exits the maze, he will be freed from the witch's enchantment and will defeat her. However, if he remains trapped within the maze forever, he will never escape.

The witch has not yet determined the directions for all the cells. She wants to assign directions to the unspecified cells in such a way that the number of starting cells from which Rostam will be trapped forever is maximized. Your task is to find the maximum number of starting cells which make Rostam trapped.

Input: The first line of the input contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$), the number of test cases.

For each test case:

- The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 1000$$$), representing the number of rows and columns in the maze.
- Each of the next $$$n$$$ lines contains a string of $$$m$$$ characters representing the directions in the maze. Each character is one of the following:   U (up)  D (down)  L (left)  R (right)  ? (unspecified direction)

It's guaranteed that the sum of $$$n \cdot m$$$ over all test cases is at most $$$10^6$$$.

Output: For each test case, print a single integer, the maximum number of starting cells from which Rostam will be trapped forever after assigning directions to the unspecified cells optimally.

Examples:
input:
3
3 3
UUU
L?R
DDD
2 3
???
???
3 3
?U?
R?L
RDL
output:
0
6
5

Note: In the first test case, all of the cells will be good no matter what you do.

In the second test case, if you assign the ?s like the picture below, all of the cells will be bad:

In the third test case, if you assign the ?s like the picture below, you will have $$$5$$$ bad cells (red-shaded cells):

Buggy Code:
import java.util.*;
import java.io.*;

public class Solution {
  public static char[][] grid;
//   public static int[][] status;
public static  Set<String> trapp;

  public static void main(String args[]) {
    Scanner sc = new Scanner(System.in);
    int T = sc.nextInt();
    char[] dir = { 'U', 'D', 'L', 'R' };
    while(T-->0) {
        int n = sc.nextInt();
        int m = sc.nextInt();
        trapp = new HashSet<>();
        grid = new char[n][m];

        for(int i=0; i<n; i++) {
            grid[i] = sc.next().toCharArray();
        }

        int ans = solve(n, m, grid);

        System.out.println(ans);
    }
  }

      private static int solve(int n, int m, char[][] grid) {
        int trappedCells = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (trapp.contains((i + " " + j)) || isTrappedCell(n, m, grid, i, j, true)) {
                    // System.out.println(i + " " + j);
                    trappedCells++;
                }
            }
        }

        return trappedCells;
    }

    private static boolean isTrappedCell(int n, int m, char[][] grid, int startX, int startY, boolean isFirst) {
        boolean[][] visited = new boolean[n][m];
        List<int[]> path = new ArrayList<>();
        int x = startX, y = startY;
        // boolean isFirst = true;
        while(true) {
            if (x<0 || x>=n || y<0 || y>=m) {
                return false;
            }
            if(grid[x][y]=='?' && isFirst) {
                boolean ans = false;
                ans |= isTrappedCell(n, m, grid, x+1, y, false);
                ans |= isTrappedCell(n, m, grid, x-1, y, false);
                ans |= isTrappedCell(n, m, grid, x, y+1, false);
                ans |= isTrappedCell(n, m, grid, x, y-1, false);
                path.add(new int[]{x, y});
                if(ans) {
                    for(int[] index : path) {
                        trapp.add((index[0] + " " + index[1]));
                    }
                }
                return ans;
            }
            if(grid[x][y] == '?' && !isFirst) {
                // System.out.println("Reversed " + x + y);
                return true;
            }

            if(visited[x][y]) {
                // System.out.println("Visited" + x + " " + y);
                for(int[] index : path) {
                        trapp.add((index[0] + " " + index[1]));
                }
                return true;
            }
            visited[x][y] = true;
            path.add(new int[]{x, y});
            isFirst = false;
            // System.out.println("Going " + grid[x][y]);
            switch(grid[x][y]) {
                case 'U': x--; break;
                case 'D': x++; break;
                case 'L': y--; break;
                case 'R': y++; break;
            }
        }
    }
}

**Instructions:**
- Focus on edge cases or scenarios that maximize the failure probability in faulty solutions.
- Due to the output length limit, you should generate a **small-scale** test input that is **complete and valid**.
- Output the test input directly, not code to generate it.

**Output format:**
```plaintext
{test input}
```

Think step by step.

Response:
```plaintext
1
3 3
???
???
???
```


**Task:**
Generate a challenging test input that exposes the bug in the buggy code of the algorithm problem:
Algorithm Problem:
Title: Trapped in the Witch's Labyrinth
time_limit_ms: 3000
memory_limit_mb: 256
Description: In the fourth labor of Rostam, the legendary hero from the Shahnameh, an old witch has created a magical maze to trap him. The maze is a rectangular grid consisting of $$$n$$$ rows and $$$m$$$ columns. Each cell in the maze points in a specific direction: up, down, left, or right. The witch has enchanted Rostam so that whenever he is in a cell, he will move to the next cell in the direction indicated by that cell.

If Rostam eventually exits the maze, he will be freed from the witch's enchantment and will defeat her. However, if he remains trapped within the maze forever, he will never escape.

The witch has not yet determined the directions for all the cells. She wants to assign directions to the unspecified cells in such a way that the number of starting cells from which Rostam will be trapped forever is maximized. Your task is to find the maximum number of starting cells which make Rostam trapped.

Input: The first line of the input contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$), the number of test cases.

For each test case:

- The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 1000$$$), representing the number of rows and columns in the maze.
- Each of the next $$$n$$$ lines contains a string of $$$m$$$ characters representing the directions in the maze. Each character is one of the following:   U (up)  D (down)  L (left)  R (right)  ? (unspecified direction)

It's guaranteed that the sum of $$$n \cdot m$$$ over all test cases is at most $$$10^6$$$.

Output: For each test case, print a single integer, the maximum number of starting cells from which Rostam will be trapped forever after assigning directions to the unspecified cells optimally.

Examples:
input:
3
3 3
UUU
L?R
DDD
2 3
???
???
3 3
?U?
R?L
RDL
output:
0
6
5

Note: In the first test case, all of the cells will be good no matter what you do.

In the second test case, if you assign the ?s like the picture below, all of the cells will be bad:

In the third test case, if you assign the ?s like the picture below, you will have $$$5$$$ bad cells (red-shaded cells):

Buggy Code:
import java.util.*;
import java.io.*;
import java.awt.Point;

public class TrappedInTheWitchsLabyrinth {
	static HashMap<Pair, List<Pair>> adj;
	static boolean[][] visited;
	static char[][] grid;

	public static void main(String[] args) throws Exception {
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st;
		PrintWriter out = new PrintWriter(System.out);
		int T = Integer.parseInt(in.readLine());
		for (int cases = 0; cases < T; cases++) {
			st = new StringTokenizer(in.readLine());
			int n = Integer.parseInt(st.nextToken());
			int m = Integer.parseInt(st.nextToken());
			grid = new char[n][m];
			adj = new HashMap<>();
			for (int i = 0; i < n; i++) {
				grid[i] = in.readLine().toCharArray();
				for (int j = 0; j < m; j++) {
					char c = grid[i][j];
					if (c == '?')
						continue;
					if (c == 'D' && i + 1 < n)
						addEdge(new Pair(i, j), new Pair(i + 1, j));
					else if (c == 'U' && i - 1 >= 0)
						addEdge(new Pair(i, j), new Pair(i - 1, j));
					else if (c == 'R' && j + 1 < m)
						addEdge(new Pair(i, j), new Pair(i, j + 1));
					else if (c == 'L' && j - 1 >= 0)
						addEdge(new Pair(i, j), new Pair(i, j - 1));
				}
			}
			visited = new boolean[n][m];
			for (int i = 0; i < n; i++) {
				if (!visited[i][0] && grid[i][0] == 'L')
					dfs(i, 0);
				if (!visited[i][m - 1] && grid[i][m - 1] == 'R')
					dfs(i, m - 1);
			}
			for (int j = 0; j < m; j++) {
				if (!visited[0][j] && grid[0][j] == 'U')
					dfs(0, j);
				if (!visited[n - 1][j] && grid[n - 1][j] == 'D')
					dfs(n - 1, j);
			}
			int ans = 0;
			for (int i = 0; i < n; i++)
				for (int j = 0; j < m; j++) {
					boolean cond1 = false;
					boolean cond2 = false;
					boolean[] vecinos = new boolean[4];
					if (!visited[i][j])
						cond1 = true;
					if (i - 1 >= 0)
						vecinos[0] = true;
					if (i + 1 < n)
						vecinos[1] = true;
					if (j - 1 >= 0)
						vecinos[2] = true;
					if (j + 1 < m)
						vecinos[3] = true;
					for (int k = 0; k < vecinos.length; k++) {
						if (vecinos[k]) {
							int x = -1;
							int y = -1;
							if (k == 0) {
								x = i - 1;
								y = j;
							} else if (k == 1) {
								x = i + 1;
								y = j;
							} else if (k == 2) {
								x = i;
								y = j - 1;
							} else {
								x = i;
								y = j + 1;
							}
							if (!visited[x][y]) {
								cond2 = true;
								break;
							}
						}
					}
					if (cond1 && cond2)
						ans++;
				}
			out.println(ans);
		}
		out.close();

	}

	static void dfs(int i, int j) {
		visited[i][j] = true;
		Pair u = new Pair(i, j);
		if (adj.get(u) == null)
			return;
		for (Pair ee : adj.get(u)) {
			int x = ee.first;
			int y = ee.second;
			if (!visited[x][y] && grid[x][y] != '?')
				dfs(x, y);
		}
	}

	static void addEdge(Pair b, Pair a) {
		if (adj.get(a) == null)
			adj.put(a, new ArrayList<>());
		adj.get(a).add(b);
	}

	static class Pair {
		int first;
		int second;

		Pair(int f, int s) {
			this.first = f;
			this.second = s;
		}

		public boolean equals(Object o) {
			Pair op = (Pair) o;
			return first == op.first && second == op.second;
		}

		public int hashCode() {
			int bits = (first ^ second * 31);
			return bits ^ (bits >> 32);
		}

		public String toString() {
			return "(" + first + ", " + second + ")";
		}

	}

}

**Instructions:**
- Focus on edge cases or scenarios that maximize the failure probability in faulty solutions.
- Due to the output length limit, you should generate a **small-scale** test input that is **complete and valid**.
- Output the test input directly, not code to generate it.

**Output format:**
```plaintext
{test input}
```

Think step by step.

Response:
To expose the bug in the provided code, we need to focus on edge cases where the algorithm might not handle unspecified directions (`?`) correctly. Specifically, we need to ensure that the code does not incorrectly mark cells as trapped when they should not be, or vice versa.

### Step-by-Step Analysis:

1. **Edge Cases:**
   - **Single Cell Maze:** A single cell maze with an unspecified direction (`?`) should always be considered trapped.
   - **Small Maze with Unspecified Directions:** A small maze with a few unspecified directions should be able to maximize the number of trapped cells.
   - **Maze with No Exit:** A maze where all cells are specified and none of them lead to an exit should be considered fully trapped.
   - **Maze with Mixed Directions:** A maze with a mix of specified and unspecified directions should be able to maximize the number of trapped cells.

2. **Test Case 1: Single Cell Maze**
   - This is a straightforward case where the single cell should always be trapped.
   ```plaintext
   1
   1 1
   ?
   ```

3. **Test Case 2: Small Maze with Unspecified Directions**
   - This case should maximize the number of trapped cells by assigning directions optimally.
   ```plaintext
   1
   3 3
   ???
   ???
   ???
   ```

4. **Test Case 3: Maze with No Exit**
   - All cells are specified and none lead to an exit.
   ```plaintext
   1
   3 3
   DLU
   RDL
   ULR
   ```

5. **Test Case 4: Maze with Mixed Directions**
   - This case should ensure that the algorithm correctly handles a mix of specified and unspecified directions.
   ```plaintext
   1
   3 3
   ?U?
   R?L
   RDL
   ```

### Chosen Test Case:
For a small-scale test input that is complete and valid, let's choose the second test case, which is a small maze with all unspecified directions. This case is particularly challenging because it requires the algorithm to correctly maximize the number of trapped cells.

```plaintext
1
3 3
???
???
???
```

This test case will expose any issues in the algorithm's ability to handle unspecified directions and maximize the number of trapped cells.