fork(35) download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int n, m;
  5. string board[51];
  6. bool visited[51][51];
  7. bool findCycle = false;
  8. int dx[] = {1, -1, 0, 0};
  9. int dy[] = {0, 0, 1, -1};
  10.  
  11. void dfs(int x, int y, int fromX, int fromY, char needColor)
  12. {
  13. if(x < 0 || x >= n || y < 0 || y >= m) return;
  14. if(board[x][y] != needColor) return;
  15. if(visited[x][y])
  16. {
  17. findCycle = true;
  18. return;
  19. }
  20. visited[x][y] = true;
  21. for(int f = 0; f < 4; f++)
  22. {
  23. int nextX = x + dx[f];
  24. int nextY = y + dy[f];
  25. if(nextX == fromX && nextY == fromY) continue;
  26. dfs(nextX, nextY, x, y, needColor);
  27. }
  28. }
  29.  
  30. int MAIN()
  31. {
  32. cin >> n >> m;
  33. for(int i = 0; i < n; i++)
  34. cin >> board[i];
  35. memset(visited, false, sizeof(visited));
  36. for(int i = 0; i < n; i++)
  37. for(int j = 0; j < m; j++)
  38. if(!visited[i][j])
  39. dfs(i, j, -1, -1, board[i][j]);
  40. cout << (findCycle ? "Yes" : "No") << endl;
  41. return 0;
  42. }
  43.  
  44. int main()
  45. {
  46. #ifdef LOCAL_TEST
  47. freopen("in.txt", "r", stdin);
  48. freopen("out.txt", "w", stdout);
  49. #endif
  50. ios :: sync_with_stdio(false);
  51. cout << fixed << setprecision(16);
  52. return MAIN();
  53. }
  54.  
Success #stdin #stdout 0s 3280KB
stdin
Standard input is empty
stdout
No