You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

对大数取模返回0的问题排查(附Java实现代码)

问题原因分析与解决办法

核心原因:变量名冲突

你定义的类成员变量long m = 1000000007L(取模常量),和方法findPaths、bfs的参数int m(网格行数)重名了。在bfs方法的取模计算(a%m+b%m+c%m+d%m)%m中,这里的m实际指向的是方法参数里的网格行数,而非你原本想要的1000000007L。比如当网格行数为1时,所有数值对1取模结果必然是0,这就是返回值始终为0的直接原因。

解决办法

将类里的取模常量重命名,避免和参数变量冲突,比如改成MOD,然后替换所有用到该常量的位置:

修改后的代码

import java.util.Arrays;

class Solution {
    long ans = 0;
    long MOD = 1000000007L; // 重命名避免冲突
    long[][][] dp;

    public int findPaths(int m, int n, int maxMove, int startRow, int startColumn) {
        dp = new long[m+2][n+2][maxMove+1];
        for(long[][] arr : dp){
            for(long[] a : arr) Arrays.fill(a,-1);
        }
        bfs(startRow,startColumn,m,n,maxMove);
        return (int)(dp[startRow][startColumn][maxMove] % MOD); // 替换为MOD
    }

    public long bfs(int x,int y,int m,int n,int moves){
        if(moves < 0) return 0;
        if(x == -1 || y == -1 || x == m || y == n) return 1;
        if(dp[x][y][moves] != -1) return dp[x][y][moves];
        
        long a = bfs(x+1,y,m,n,moves-1);
        long b = bfs(x,y+1,m,n,moves-1);
        long c = bfs(x-1,y,m,n,moves-1);
        long d = bfs(x,y-1,m,n,moves-1);
        dp[x][y][moves] = (a%MOD + b%MOD + c%MOD + d%MOD) % MOD; // 替换为MOD
        return dp[x][y][moves];
    }   
}

内容的提问来源于stack exchange,提问作者Harsha Vardhan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 22:15:39