#include <bits/stdc++.h>
using namespace std;

bool isBorder(int r, int c, int rows, int cols) {
    return r == 0 || r == rows - 1 || c == 0 || c == cols - 1;
}

int getExpectedValue(int idx) {
    if (idx == 0) return 1;
    return (idx % 2 == 1) ? 2 : 0;
}

int solution(vector<vector<int>>& matrix) {
    int rows = matrix.size();
    int cols = matrix[0].size();
    int maxLen = 0;

    // All 4 diagonal directions
    vector<pair<int, int>> directions = {
        {1, 1},   // ↘
        {1, -1},  // ↙
        {-1, 1},  // ↗
        {-1, -1}  // ↖
    };

    for (int r = 0; r < rows; ++r) {
        for (int c = 0; c < cols; ++c) {
            // Only start if the cell is 1 (pattern starts with 1)
            if (matrix[r][c] != 1) continue;

            for (auto& dir : directions) {
                int len = 0;
                int i = r, j = c;
                while (i >= 0 && i < rows && j >= 0 && j < cols) {
                    if (matrix[i][j] != getExpectedValue(len)) break;
                    len++;
                    i += dir.first;
                    j += dir.second;
                }

                // Check if the last valid position was on the border
                int last_i = r + dir.first * (len - 1);
                int last_j = c + dir.second * (len - 1);
                if (len > 0 && isBorder(last_i, last_j, rows, cols)) {
                    maxLen = max(maxLen, len);
                }
            }
        }
    }

    return maxLen;
}

int main() {
    vector<vector<int>> matrix = {
        {0, 0, 1, 2},
        {0, 2, 2, 2},
        {2, 1, 0, 1}
    };

    cout << solution(matrix) << endl; // Output: 3
    return 0;
}
