2023-06-18 Daily Challenge
Today I have done leetcode's June LeetCoding Challenge with cpp
.
June LeetCoding Challenge 18
Description
Number of Increasing Paths in a Grid
You are given an m x n
integer matrix grid
, where you can move from a cell to any adjacent cell in all 4
directions.
Return the number of strictly increasing paths in the grid such that you can start from any cell and end at any cell. Since the answer may be very large, return it modulo 109 + 7
.
Two paths are considered different if they do not have exactly the same sequence of visited cells.
Example 1:
Input: grid = [[1,1],[3,4]] Output: 8 Explanation: The strictly increasing paths are: - Paths with length 1: [1], [1], [3], [4]. - Paths with length 2: [1 -> 3], [1 -> 4], [3 -> 4]. - Paths with length 3: [1 -> 3 -> 4]. The total number of paths is 4 + 3 + 1 = 8.
Example 2:
Input: grid = [[1],[2]] Output: 3 Explanation: The strictly increasing paths are: - Paths with length 1: [1], [2]. - Paths with length 2: [1 -> 2]. The total number of paths is 2 + 1 = 3.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 1000
1 <= m * n <= 105
1 <= grid[i][j] <= 105
Solution
class Solution {
const int MOD = 1e9 + 7;
const int MOVES[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
int rows;
int cols;
int solve(
int row,
int col,
int parent,
const vector<vector<int>>& grid,
vector<vector<int>> &dp
) {
if(row < 0 || row >= rows) return 0;
if(col < 0 || col >= cols) return 0;
if(grid[row][col] <= parent) return 0;
if(dp[row][col] != -1) return dp[row][col];
int result = 1;
for(int m = 0; m < 4; ++m) {
int newRow = row + MOVES[m][0];
int newCol = col + MOVES[m][1];
result += solve(newRow, newCol, grid[row][col], grid, dp);
result %= MOD;
}
dp[row][col] = result;
return result;
}
public:
int countPaths(vector<vector<int>>& grid) {
rows = grid.size();
cols = grid.front().size();
vector<vector<int>> dp(rows, vector<int>(cols, -1));
for(int r = 0; r < rows; ++r) {
for(int c = 0; c < cols; ++c) {
if(dp[r][c] == -1) solve(r, c, -1, grid, dp);
}
}
int answer = 0;
for(int r = 0; r < rows; ++r) {
for(int c = 0; c < cols; ++c) {
answer += dp[r][c];
answer %= MOD;
}
}
return answer;
}
};
// Accepted
// 36/36 cases passed (292 ms)
// Your runtime beats 75.49 % of cpp submissions
// Your memory usage beats 80.56 % of cpp submissions (43.4 MB)