Leetcode 1594. 矩阵的最大非负积(DAY 54) ---- 动态规划学习期(双百解法)(重邮最近好冷好冷 几天短袖几天羽绒服)

原题题目

Leetcode 1594. 矩阵的最大非负积(DAY 54) ---- 动态规划学习期(双百解法)(重邮最近好冷好冷 几天短袖几天羽绒服)



代码实现(首刷自解)

int maxProductPath(int** grid, int gridSize, int* gridColSize){
    long long dp1[16][16],dp2[16][16],flag = 0,i,j;
    memset(dp1,0,sizeof(dp1));
    memset(dp2,0,sizeof(dp2));
    for(i=0;i<gridSize;i++)
    {
        for(j=0;j<gridColSize[0];j++)
        {
            if(!grid[i][j]) flag = 1;
            if(grid[i][j] < 0)
            {
                if(!i && !j)    
                    dp1[i][j] = grid[i][j];
                else if(!i) 
                {
                    dp1[i][j] = dp2[i][j-1] * grid[i][j];
                    dp2[i][j] = dp1[i][j-1] * grid[i][j];
                }
                else if(!j)
                {
                    dp1[i][j] = dp2[i-1][j] * grid[i][j];
                    dp2[i][j] = dp1[i-1][j] * grid[i][j];
                }
                else
                {
                    dp1[i][j] = fmin(dp2[i-1][j] * grid[i][j],dp2[i][j-1] * grid[i][j]);
                    dp2[i][j] = fmax(dp1[i-1][j] * grid[i][j],dp1[i][j-1] * grid[i][j]);
                }
            }
            else
            {
                if(!i && !j)    
                    dp2[i][j] = grid[i][j];
                else if(!i) 
                {
                    dp1[i][j] = dp1[i][j-1] * grid[i][j];
                    dp2[i][j] = dp2[i][j-1] * grid[i][j];
                }
                else if(!j)
                {
                    dp1[i][j] = dp1[i-1][j] * grid[i][j];
                    dp2[i][j] = dp2[i-1][j] * grid[i][j];
                }
                else
                {
                    dp1[i][j] = fmin(dp1[i][j-1] * grid[i][j],dp1[i-1][j] * grid[i][j]);
                    dp2[i][j] = fmax(dp2[i][j-1] * grid[i][j],dp2[i-1][j] * grid[i][j]);
                }
            }
        }
    }
    if(dp2[gridSize-1][gridColSize[0]-1] <  0 || (!dp2[gridSize-1][gridColSize[0]-1]) && !flag)  return -1;
    else return dp2[gridSize-1][gridColSize[0]-1] % 1000000007;
}


双百截图

Leetcode 1594. 矩阵的最大非负积(DAY 54) ---- 动态规划学习期(双百解法)(重邮最近好冷好冷 几天短袖几天羽绒服)

上一篇:54. 螺旋矩阵 + 蛇形矩阵打印 + 螺旋矩阵


下一篇:剑指Offer-54 0~n-1中缺失的数字