#include <algorithm>
#include <functional>
#include <iostream>
#include <vector>
using namespace std;
int solution(int m, int n, vector<vector<int>> &a) {
vector<vector<bool>> visited(m, vector<bool>(n, false));
function<int(int, int, bool)> dfs = [&](int x, int y, bool isUp) -> int {
visited[x][y] = true;
int maxPath = 0;
vector<pair<int, int>> directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
for (auto &dir : directions) {
int nx = x + dir.first;
int ny = y + dir.second;
if (nx >= 0 && nx < m && ny >= 0 && ny < n && !visited[nx][ny]) {
if ((isUp && a[nx][ny] < a[x][y]) || (!isUp && a[nx][ny] > a[x][y])) {
maxPath = max(maxPath, dfs(nx, ny, !isUp));
}
}
}
visited[x][y] = false;
return maxPath + 1;
};
int maxSteps = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
maxSteps = max(maxSteps, dfs(i, j, true));
maxSteps = max(maxSteps, dfs(i, j, false));
}
}
return maxSteps - 1;
}
int main() {
vector<vector<int>> a1 = {{1, 2}, {4, 3}};
cout << (solution(2, 2, a1) == 3) << endl;
vector<vector<int>> a2 = {{10, 1, 6}, {5, 9, 3}, {7, 2, 4}};
cout << (solution(3, 3, a2) == 8) << endl;
vector<vector<int>> a3 = {
{8, 3, 2, 1}, {4, 7, 6, 5}, {12, 11, 10, 9}, {16, 15, 14, 13}};
cout << (solution(4, 4, a3) == 11) << endl;
}