The simple brute force method of manually implementing each bounce is sufficient to solve the problem, if we can prove that the ball will bound no more than O ( n + m ) \mathcal O (n+m) O(n+m) times
If you start enumerating each bounce, you will notice that the ball will end up in no more than 2 ⋅ ( n + m ) 2\cdot (n+m) 2⋅(n+m) places after one bounce, since they can only bounce at the border of the grid. Moreover, since the ball only goes in the diagonal direction, the ball only has two possible directions when it hits the wall (parallel to the main diagonal or the secondary diagonal), meaning that the ball only has 4 ⋅ ( n + m ) 4\cdot (n+m) 4⋅(n+m) possible states.
With this conclusion, we can be sure that the ball will bounce for at most 4 ⋅ n ⋅ m 4\cdot n \cdot m 4⋅n⋅m times before it hits the objective (assuming feasibility). Then, the rest can be done with ad-hoc enumeration that ends when the bounce count exceeds the deduced limit.
Time Complexity: O ( 4 ⋅ ( n + m ) ) \mathcal O(4 \cdot (n + m)) O(4⋅(n+m))
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
const int dx[]={-1,1};
const int dy[]={-1,1};
int n,m,sx,sy,ex,ey,u,v;
inline int read()
{
int s=0,w=1;
char ch=getchar();
while(ch<'0' || ch>'9'){if(ch=='-')w=-1;ch=getchar();}
while(ch>='0' && ch<='9')s=(s<<3)+(s<<1)+(ch^48),ch=getchar();
return s*w;
}
bool move(int &x,int &y,int &u,int &v)
{
while(x+dx[u]>=1 && x+dx[u]<=n && y+dy[v]>=1 && y+dy[v]<=m)
{
x+=dx[u],y+=dy[v];
if(x==ex && y==ey)return true;
}
if(!(x+dx[u]>=1 && x+dx[u]<=n))u^=1;
if(!(y+dy[v]>=1 && y+dy[v]<=m))v^=1;
return false;
}
int main()
{
// freopen("in.txt","r",stdin);
int T=read();
while(T--)
{
n=read(),m=read();
sx=read(),sy=read();
ex=read(),ey=read();
char s[5];
scanf("%s",s);
u=(s[0]=='D');
v=(s[1]=='R');
int ans=0;
for(int i=1;i<=5*(n+m);++i)
{
if(sx==ex && sy==ey){printf("%d\n",ans);goto GG;}
if(move(sx,sy,u,v)){printf("%d\n",ans);goto GG;}
++ans;
}
puts("-1");
GG:;
}
return 0;
}