/*
* @lc app=leetcode id=329 lang=cpp
*
* [329] Longest Increasing Path in a Matrix
*/
class Solution {
public:
int longestIncreasingPath(vector<vector<int>>& matrix) {
const int M = matrix.size(), N = M == 0 ? 0 : matrix[0].size();
if (M == 0 || N == 0) return 0;
vector<vector<int>> m;
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
m.push_back({matrix[i][j], i, j});
}
}
sort(m.begin(), m.end(), [](const auto &a, const auto &b) {
return a[0] > b[0];
});
vector<vector<int>> dirs = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
vector<vector<int>> dp(M, vector<int>(N, 1));
int res = 0;
for (const auto &e : m) {
const int i = e[1], j = e[2];
for (const auto &dir : dirs) {
const int x = i + dir[0];
const int y = j + dir[1];
if (x >= 0 && x < M && y >= 0 && y < N && matrix[x][y] > matrix[i][j]) {
dp[i][j] = max(dp[i][j], dp[x][y] + 1);
}
}
res = max(res, dp[i][j]);
}
return res;
}
};