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

LeetCode题目Word Search II实现遇java.lang.ArrayIndexOutOfBoundsException报错求助

排查数组越界:Word Search II中的循环条件笔误

你遇到的ArrayIndexOutOfBoundsException问题根源其实非常隐蔽——双重循环里的内层循环条件写错了!

看你findWords方法里的这段代码:

for(int i=0; i<board.length; i++){
    for(int j=0; i<board[0].length; j++){ // 这里的条件错误地用了i而不是j!
        dfs(board,i,j,root,result);
    }
}

错误原因分析

内层循环的终止条件写成了i<board[0].length,而不是j<board[0].length。这会引发连锁问题:

  • 外层循环的i会正常遍历每一行,但内层的j会不受列数限制一直递增,直到超出board[0].length的合法索引范围。
  • 当j超过列的最大索引(比如列数为4时,索引最大是3,j变成4),调用dfs时执行char c = board[i][j];就会直接触发数组越界异常。

修正后的代码

只需把内层循环的条件改成j<board[0].length,同时建议增加空输入的判断让代码更健壮:

public List<String> findWords(char[][] board, String[] words) { 
    List<String> result = new ArrayList(); 
    // 增加空输入判断,避免空数组访问board[0].length
    if(board == null || board.length == 0 || board[0].length == 0) return result;
    TrieNode root = buildTrie(words); 
    for(int i=0; i<board.length; i++){ 
        for(int j=0; j<board[0].length; j++){ // 修正为j<board[0].length
            dfs(board,i,j,root,result); 
        } 
    } 
    return result; 
}

额外验证

你的dfs方法里的边界判断是正确的:

if(i>0) dfs(board, i-1,j, root, result); 
if(j>0) dfs(board, i, j-1, root,result);
if(i<board.length-1) dfs(board, i+1, j, root, result);
if(j<board[0].length-1) dfs(board, i, j+1, root, result);

这些判断确保了递归时不会越界,所以核心问题就是循环条件的笔误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 17:09:06