1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
   | class Solution { public:     int longestIncreasingPath(vector<vector<int>>& matrix) {         rows = matrix.size();         if (rows == 0)             return 0;         cols = matrix[0].size();         vector<vector<int>> dp(rows, vector<int>(cols, -1));         int ans = 0;
          for (int i = 0; i < rows; i++)              for (int j = 0; j < cols; j++)                  ans = max(ans, dfs(matrix, dp, i, j));
          return ans;     }
  private:     int dfs(const vector<vector<int>>& matrix, vector<vector<int>>& dp, int x, int y) {         if (x < 0 || x >= rows || y < 0 || y >= cols)             return 0;         if (dp[x][y] != -1)             return dp[x][y];                  for (int k = 0; k < 4; k++) {             int nx = x + dx[k], ny = y + dy[k];             if (nx >= 0 && nx < rows && ny >= 0 && ny < cols && matrix[nx][ny] > matrix[x][y])                 dp[x][y] = max(dp[x][y], dfs(matrix, dp, nx, ny) + 1);         }         if (dp[x][y] == -1)             dp[x][y] = 1;                  return dp[x][y];     }
      int rows, cols;     const int dx[4] = {-1, 1, 0, 0};     const int dy[4] = {0, 0, -1, 1}; };
  |