进行dfs,dfs中为了防止访问已经访问的节点,使用visit进行标记。但当子问题做完需要将visit变0,因为其它路径可以访问

import java.util.*;

public class Solution {
    public int[][] visit = new int[21][21];
    public boolean dfs(char[][] matrix, String word, int i, int j, int index){
        if(index == word.length())return true;
        if(i<0||i>=matrix.length||j<0||j>=matrix[0].length)return false;
        if(visit[i][j] == 1)return false;
        if(word.charAt(index) != matrix[i][j])return false;
        
        boolean ans = false;
        visit[i][j] = 1;
        ans = bfs(matrix,word,i-1,j,index+1)||bfs(matrix,word,i,j-1,index+1)||bfs(matrix,word,i+1,j,index+1)||bfs(matrix,word,i,j+1,index+1);
        visit[i][j] = 0;
        return ans;
    }
      
    public boolean hasPath (char[][] matrix, String word) {
        // write code here
        for(int i = 0; i <matrix.length;i++)
            for(int j = 0; j< matrix[0].length;j++)
                if(dfs(matrix,word,i,j,0))return true;
        return false;
    }
}