fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. bool isBorder(int r, int c, int rows, int cols) {
  5. return r == 0 || r == rows - 1 || c == 0 || c == cols - 1;
  6. }
  7.  
  8. int getExpectedValue(int idx) {
  9. if (idx == 0) return 1;
  10. return (idx % 2 == 1) ? 2 : 0;
  11. }
  12.  
  13. int solution(vector<vector<int>>& matrix) {
  14. int rows = matrix.size();
  15. int cols = matrix[0].size();
  16. int maxLen = 0;
  17.  
  18. // All 4 diagonal directions
  19. vector<pair<int, int>> directions = {
  20. {1, 1}, // ↘
  21. {1, -1}, // ↙
  22. {-1, 1}, // ↗
  23. {-1, -1} // ↖
  24. };
  25.  
  26. for (int r = 0; r < rows; ++r) {
  27. for (int c = 0; c < cols; ++c) {
  28. // Only start if the cell is 1 (pattern starts with 1)
  29. if (matrix[r][c] != 1) continue;
  30.  
  31. for (auto& dir : directions) {
  32. int len = 0;
  33. int i = r, j = c;
  34. while (i >= 0 && i < rows && j >= 0 && j < cols) {
  35. if (matrix[i][j] != getExpectedValue(len)) break;
  36. len++;
  37. i += dir.first;
  38. j += dir.second;
  39. }
  40.  
  41. // Check if the last valid position was on the border
  42. int last_i = r + dir.first * (len - 1);
  43. int last_j = c + dir.second * (len - 1);
  44. if (len > 0 && isBorder(last_i, last_j, rows, cols)) {
  45. maxLen = max(maxLen, len);
  46. }
  47. }
  48. }
  49. }
  50.  
  51. return maxLen;
  52. }
  53.  
  54. int main() {
  55. vector<vector<int>> matrix = {
  56. {0, 0, 1, 2},
  57. {0, 2, 2, 2},
  58. {2, 1, 0, 1}
  59. };
  60.  
  61. cout << solution(matrix) << endl; // Output: 3
  62. return 0;
  63. }
  64.  
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
3