原题地址:https://www.nowcoder.com/practice/2a49359695a544b8939c77358d29b7e6?tpId=13&tqId=1517966&ru=/practice/72a5a919508a4251859fb2cfb987a0e6&qru=/ta/coding-interviews/question-ranking
题解:回溯法经典题
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param matrix char字符型二维数组
* @param word string字符串
* @return bool布尔型
*/
public boolean hasPath (char[][] matrix, String word) {
// write code here
if(matrix.length == 0 || matrix[0].length == 0) return false;
boolean[][] flag = new boolean[matrix.length][matrix[0].length];//记录i,j位置元素是否被使用
for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < matrix[0].length; j ++){
//每一个位置都可能是初始位置
boolean res = helper(matrix, word, flag, 0, i, j);
if(res) return true;
}
}
return false;
}
public boolean helper(char[][] matrix, String word, boolean[][] flag, int index, int i, int j){
if(index == word.length()) return true;
if(i < 0 || i >= matrix.length || j < 0 || j >= matrix[0].length) return false;
if(!flag[i][j] && matrix[i][j] == word.charAt(index)){
flag[i][j] = true;
//四个方向继续寻找,如果其中一个为true,则返回true
if (helper(matrix, word, flag, index+1, i + 1, j) ||
helper(matrix, word, flag, index+1, i - 1, j) ||
helper(matrix, word, flag, index+1, i, j + 1) ||
helper(matrix, word, flag, index+1, i, j - 1)) return true;
flag[i][j] = false;
}
return false;
}
}