Leetcode-3665

Twisted Mirror Path Count

Time complexity: $O(mn)$

 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
#include <iostream>
#include <vector>
#include <cmath>

const int M = 1'000'000'007;

class Solution {
public:
    int uniquePaths(std::vector<std::vector<int>>& grid) {
        int m = grid.size();
        int n = grid[0].size();
        std::vector<std::pair<int, int>> dp(n); // {right, down}
        
        dp[0] = {0, 1};
        for (int j = 1; j < n; ++j) {
            dp[j] = {1, 0};
            if (grid[0][j]) {
                break;
            }
        }
        
        for (int i = 1; i < m; ++i) {
            if (grid[i - 1][0]) {
                dp[0] = {0, 0};
            }
            for (int j = 1; j < n; ++j) {
                dp[j] = {grid[i][j - 1] ? dp[j - 1].second : (dp[j - 1].first + dp[j - 1].second) % M, grid[i - 1][j] ? dp[j].first : (dp[j].first + dp[j].second) % M};
            }
        }
        
        return (dp.back().first + dp.back().second) % M;
    }
};

Leetcode-3665

Licensed under CC BY-NC-SA 4.0