아주 전형적으로 DFS 재귀로도 풀 수 있고, 최적값을 찾는 문제이기도 하므로 BFS로도 풀 수 있는 문제입니다. (미리 말씀드리지만, DFS가 훨씬 빠르게 풀 수 있는 문제입니다.)
#include <iostream>
#include <queue>
#include <tuple>
using namespace std;
constexpr int d[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
int R, C, answer;
char board[20][20];
bool alpha[26];
void solve(int cy, int cx, int cnt)
{
answer = max(answer, cnt);
for (auto i : d) {
int ny = cy + i[0], nx = cx + i[1];
if (ny < 0 || nx < 0 || ny >= R || nx >= C) continue;
int next_alpha = board[ny][nx] - 'A';
if (alpha[next_alpha]) continue;
alpha[next_alpha] = true;
solve(ny, nx, cnt + 1);
alpha[next_alpha] = false;
}
}
int main()
{
ios::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
cin >> R >> C;
for (int y = 0; y < R; y++)
for (int x = 0; x < C; x++)
cin >> board[y][x];
alpha[board[0][0] - 'A'] = true;
solve(0, 0, 1);
cout << answer << '\n';
return 0;
}
#include <iostream>
#include <queue>
#include <tuple>
using namespace std;
constexpr int d[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
int R, C;
char board[20][20];
int get_length(int num) {
int ret = 0;
for (int i = 0; i < 32; i++)
if (num & (1 << i)) ret++;
return ret;
}
int main()
{
ios::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
cin >> R >> C;
for (int y = 0; y < R; y++)
for (int x = 0; x < C; x++)
cin >> board[y][x];
queue<tuple<int, int, int>> q;
q.emplace(0, 0, (1 << (board[0][0] - 'A')));
int answer = 1;
while (!q.empty()) {
int cy, cx, history; tie(cy, cx, history) = q.front();
q.pop();
answer = max(answer, get_length(history));
for (auto i : d) {
int ny = cy + i[0], nx = cx + i[1];
if (ny < 0 || nx < 0 || ny >= R || nx >= C ||
(history & (1 << (board[ny][nx] - 'A')))) continue;
q.emplace(ny, nx, history | (1 << (board[ny][nx] - 'A')));
}
}
cout << answer << '\n';
return 0;
}