1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| #include <iostream> #include <cstring> #define N 21
using namespace std;
char g[N][N]; bool st[30]; int n, m; int ans;
int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
void dfs(int x, int y, int dist) { for (int i = 0; i < 4; ++ i) { int a = x + dx[i], b = y + dy[i];
if (a >= 0 && a < n && b >= 0 && b < m && !st[g[a][b] - 'A']) { st[g[a][b] - 'A'] = true; dfs(a, b, dist + 1); st[g[a][b] - 'A'] = false; } else ans = max(ans, dist); } }
int main() { cin >> n >> m;
for (int i = 0; i < n; ++ i) for (int j = 0; j < m; ++ j) cin >> g[i][j];
st[g[0][0] - 'A'] = true; dfs(0, 0, 1); cout << ans << endl;
return 0; }
|