DFS로 접근하여 풀긴 풀었는데 수행시간이 다른 C++정답자들의 2배가 나왔다. 어디서 문제가 생긴지 모르겠다...
#include <iostream>
#include <vector>
using namespace std;
vector <vector <char>> graph;
vector <bool> visited(30, false);//알파벳 방문
vector<pair<int, int>>direction{ {1, 0}, {0, 1}, {-1, 0}, {0, -1} };
int R, C;
int max_count = 0;
void input_graph()
{
int i, j;
cin >> R >> C;
graph.resize(R, vector<char>(C));
for (i = 0; i < R; i++)
{
for (j = 0; j < C; j++)
{
cin >> graph[i][j];
}
}
/*for (i = 0; i < R; i++)
{
for (j = 0; j < C; j++)
{
cout << graph[i][j];
}
cout << "\n";
}*/
return;
}
void DFS(int start_x, int start_y, int count)
{
int i = 0;
int next_x, next_y, next_index;
int index = graph[start_y][start_x] - 'A';
if (max_count < count)
{
max_count = count;
}
visited[index] = true;
for (i = 0; i < direction.size(); i++)
{
next_x = start_x + direction[i].first;
next_y = start_y + direction[i].second;
if ((next_x >= 0 && next_x < C) && (next_y >= 0 && next_y < R))
{
next_index = graph[next_y][next_x] - 'A';
if (visited[next_index] == false)
{
DFS(next_x, next_y, count + 1);
}
}
}
count--;
visited[index] = false;
return;
}
void find_graph()
{
DFS(0, 0, 1);
cout << max_count << "\n";
}
int main(void)
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
input_graph();
find_graph();
return 0;
}