当前位置:网站首页>2328. Number of incremental paths in the grid graph (memory search)

2328. Number of incremental paths in the grid graph (memory search)

2022-07-06 04:15:00 Harris-H

2328. The number of incremental paths in the grid graph ( Memory search )

Diffusion around the principle matrix , It can also be memorized dp.

Time complexity : O ( n m ) O(nm) O(nm)

class Solution {
    
public:
    int countPaths(vector<vector<int>>& a) {
    
        int n =a.size(),m=a[0].size();
        vector<vector<int> >f(n,vector<int>(m,-1));
        int d[4][2] ={
    0,1,0,-1,1,0,-1,0};
        const int mod = 1e9+7;
        function<int(int,int)> dfs = [&](int x,int y){
    
            if(~f[x][y]) return f[x][y];
            int ans = 1;
            for(int i=0;i<4;i++){
    
                int nx = x+d[i][0],ny=y+d[i][1];
                if(nx>=0 && nx<n && ny>=0 && ny<m && a[nx][ny] >a[x][y]){
    
                    ans=(ans+dfs(nx,ny))%mod;
                }
            }
            return f[x][y] =ans;
        };
        int ans=0;
        for(int i=0;i<n;i++)
            for(int j=0;j<m;j++) ans=(ans+dfs(i,j))%mod;
        return ans;
    }
};
原网站

版权声明
本文为[Harris-H]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060411331979.html