You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
1.5 KiB

#include<bits/stdc++.h>
using namespace std;
const int N = 110;
#define x first
#define y second
typedef pair<int, int> PII;
int a[N][N];
int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, -1, 1};
int n, m, Max;
vector<PII> s;
/**
测试数据
4 4
BLQB
BBQS
SBQL
QQQQ
输出
2
3 3
LSB
QBQ
BSL
输出
-1
*/
/**
* 功能:深度优先搜索
* @param x 横坐标
* @param y 纵坐标
* @param step 步数
*/
void dfs(int x, int y, int step) {
//如果死循环,一直
if (step > n * m) {
cout << -1 << endl;
exit(0);
}
//更新步数
Max = max(Max, step);
//4个方向
for (int i = 0; i <= 3; i++) {
int tx = x + dx[i];
int ty = y + dy[i];
//如果出界
if (tx < 1 || tx > n || ty < 1 || ty > m) continue;
//下一步与期望值对比
if (a[tx][ty] == a[x][y] + 1 || (a[tx][ty] == 1 && a[x][y] == 4))
dfs(tx, ty, step + 1);
}
}
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++) {
char x;
cin >> x;
//记录起点
if (x == 'L')
a[i][j] = 1, s.push_back({i, j});
else if (x == 'Q') a[i][j] = 2;
else if (x == 'B') a[i][j] = 3;
else if (x == 'S') a[i][j] = 4;
}
//模拟从每个起点开始
for (int i = 0; i < s.size(); i++)
dfs(s[i].x, s[i].y, 1);
//长度除以4
cout << Max / 4 << endl;
return 0;
}