解决只能走一遍的办法就是把 在遍历时把
matrix[i][j] = '.';
改为别的字母
然后再结束时改回来;
matrix[i][j] = tmp;
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param matrix char字符型二维数组 * @param word string字符串 * @return bool布尔型 */ public boolean hasPath (char[][] matrix, String word) { if(word.length() == 0) return true; for(int i = 0;i<matrix.length;i++){ for(int j = 0;j<matrix[0].length;j++){ if(helper(matrix,i,j,word)) return true; } } return false; } public boolean helper (char[][] matrix, int i, int j, String word) { if(word.length() == 0) return true; if(i<0 || j < 0 || i >= matrix.length || j >= matrix[0].length) return false; if(word.charAt(0) == matrix[i][j] ){ char tmp = matrix[i][j]; matrix[i][j] = '.'; boolean res = helper(matrix,i-1,j,word.substring(1,word.length())) || helper(matrix,i+1,j,word.substring(1,word.length())) || helper(matrix,i,j+1,word.substring(1,word.length())) || helper(matrix,i,j-1,word.substring(1,word.length())); matrix[i][j] = tmp; return res; } else return false; } }