Problem - F - Codeforces
就是很普通的模拟,我们模拟这个点走的过程,如果走到一个之前走到的状态就说明陷入了循环,此时就是无解,状态可以用坐标和方向来表示,坐标 = (横坐标 - 1) * 列数 + 列坐标,方向就模拟好了,来看看手法吧,代码有注释
参考代码:
#include <bits/stdc++.h>
#define x first
#define y second
#define endl '\n'
#define int long long
#define NO {puts("NO"); return;}
#define YES {puts("YES"); return;}
using namespace std;
typedef long long ll;
typedef pair<int, int> PII;
const int mod = 1e9 + 7;
const int N = 1e6 + 10, INF = 1e18;
int n, m;
int a[N], b[N];
string now ;
map<string, PII> dir;
int read()
{
int x = 0, f = 1;
char c = getchar();
while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
return x * f;
}
bool check_n(int x)
{
return (x >= 1 && x <= n);
}
bool check_m(int y)
{
return (y >= 1 && y <= m);
}
void solve()
{
int i1, j1, i2, j2;
cin >> n >> m >> i1 >> j1 >> i2 >> j2 >> now;
map<int, map<string, int>> vis;
dir["DL"] = {1, -1}, dir["DR"] = {1, 1}, dir["UR"] = {-1, 1}, dir["UL"] = {-1, -1};
// 先定义四个方向对应的操作
//然后我们撞墙的时候方向是相反变化的,比如上下撞墙了 D <-> U , 左右撞墙了 L <-> R
if(i1 == i2 && j1 == j2) { // 先特判掉不需要走就结束的
cout << 0 << endl;
return ;
}
int cnt = 0;
while(1) {
if(vis[(i1 - 1) * m + j1][now]) { // 走进循环了
cout << "-1" << endl;
return ;
}
vis[(i1 - 1) * m + j1][now] = 1; // 记录一下,当前状态已经被走了
i1 += dir[now].x, j1 += dir[now].y;
if(!check_n(i1) || !check_m(j1)) { // 撞墙了
cnt ++ ;
int tmp1 = i1 - dir[now].x, tmp2 = j1 - dir[now].y; // 记录一下撞墙之前的位置
if(!check_n(i1)) { // 上下撞墙了
if(now[0] == 'D') now[0] = 'U';
else now[0] = 'D';
}
if(!check_m(j1)){ // 左右撞墙了
if(now[1] == 'L') now[1] = 'R';
else now[1] = 'L';
}
i1 = tmp1 + dir[now].x, j1 = tmp2 + dir[now].y; // 把方向改正确之后,求出现在的位置
}
if(i1 == i2 && j1 == j2) break;
}
cout << cnt << endl;
return;
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t = 1;
cin >> t;
while(t -- ) solve();
return 0;
}