맞았지만 이번에도 너무 비효율적이다. ch배열을 이용하여 이전에 방문한 지점이라면 continue했다. 하나의 점에 대해 일일이 DFS를 하고, 끝났으면 모든 ch배열을 다시 초기화하였다.
#include <iostream>
#include <algorithm>
using namespace std;
char map[51][51];
int ch[51][51];
int dx[4] = { 1,0,-1,0 };
int dy[4] = { 0,1,0,-1 };
int n, m;
void DFS(int x, int y, int prex, int prey, char color) {
if (ch[x][y]==1) {
cout << "Yes" << '\n';
exit(0);
}
else {
ch[x][y] = 1;
for (int i=0; i < 4; i++) {
int xx = x + dx[i];
int yy = y + dy[i];
if (xx > n || xx<1 || yy>m || yy < 1) continue;
if (xx == prex && yy == prey) continue;
if (map[xx][yy] != color) continue;
DFS(xx, yy, x, y, map[xx][yy]);
}
}
}
int main() {
ios_base::sync_with_stdio(false);
//int n, m;
//freopen("in1.txt", "rt", stdin);
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> map[i][j];
}
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
DFS(i, j, 0, 0, map[i][j]);
//cout << map[i][j] << " ";
for (int x = 1; x <= n; x++) {
for (int y = 1; y <= m; y++) {
ch[x][y] = 0;
}
}
}
//cout << '\n';
}
cout << "No" << '\n';
return 0;
}