Advertisement
LikeRampage

C++ 329. Longest Increasing Path in a Matrix CHATGPT UNLIMITED

Apr 20th, 2024
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. cpp
  2. #include <vector>
  3. #include <algorithm>
  4.  
  5. class Solution {
  6. public:
  7. int longestIncreasingPath(std::vector<std::vector<int>>& matrix) {
  8. if (matrix.empty()) {
  9. return 0;
  10. }
  11.  
  12. int rows = matrix.size();
  13. int cols = matrix[0].size();
  14. int maxPath = 0;
  15.  
  16. std::vector<std::vector<int>> dp(rows, std::vector<int>(cols, 0));
  17.  
  18. for (int i = 0; i < rows; i++) {
  19. for (int j = 0; j < cols; j++) {
  20. maxPath = std::max(maxPath, dfs(matrix, dp, i, j, rows, cols));
  21. }
  22. }
  23.  
  24. return maxPath;
  25. }
  26.  
  27. private:
  28. int dfs(std::vector<std::vector<int>>& matrix, std::vector<std::vector<int>>& dp, int i, int j, int rows, int cols) {
  29. if (dp[i][j] != 0) {
  30. return dp[i][j];
  31. }
  32.  
  33. int dirs[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
  34. int maxPath = 1;
  35.  
  36. for (auto dir : dirs) {
  37. int x = i + dir[0];
  38. int y = j + dir[1];
  39.  
  40. if (x >= 0 && x < rows && y >= 0 && y < cols && matrix[x][y] > matrix[i][j]) {
  41. maxPath = std::max(maxPath, 1 + dfs(matrix, dp, x, y, rows, cols));
  42. }
  43. }
  44.  
  45. dp[i][j] = maxPath;
  46. return maxPath;
  47. }
  48. };
  49.  
  50.  
  51. In this implementation, the `longestIncreasingPath` function initializes a dynamic programming table `dp` to store the length of the longest increasing path starting from each cell in the matrix. It then iterates through each cell in the matrix and uses a depth-first search (dfs) function to calculate the longest increasing path starting from that cell.
  52.  
  53. The `dfs` function recursively explores all possible directions from a cell and updates the `dp` table with the length of the longest increasing path starting from that cell. Finally, the `longestIncreasingPath` function returns the maximum path length found in the matrix.
Tags: C++
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement