/** * @ClassName Solution * @Author wangyudi * @Date 2019/7/14 16:13 * @Version 1.0 * @Description */ class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } public class Solution { public boolean findPath(char[][] matrix, String str) { //INPUT with invalid Deal IF (STR == null || Matrix == null ) return to false ; // The following default input is a rectangular two-dimensional array of valid int rows = matrix.length; int cols = Matrix [0 ] .length; Boolean [] = visited new new Boolean [rows cols *]; // stored the array element corresponding to whether the information has been accessed char [] = charStr str.toCharArray (); int pathIndex = 0; // record the need to find the starting end of the string Boolean Result = to false ; for ( int row = 0; row < rows; row++) { for (int col = 0; col < cols; col++) { if (findPathCore(matrix, charStr, pathIndex, row, col, rows, cols, visited)) { result = true; break; } } } return result; } /** * 查找路径的迭代函数 * @param matrix * @param charStr * @param pathIndex * @param row * @Param COL * @param rows * @param cols * @param visited * @return * / Private Boolean findPathCore ( char [] [] Matrix, char [] charStr, int pathIndex, int Row, int COL, int rows, int cols, Boolean [] visited) { // if judged to have been found string 1 iF (pathIndex == charStr.length) return to true ; Boolean= Result to false ; // 2-dimensional array of characters is determined whether the corresponding character string IF (Row> Row = 0 && <&& rows COL > = 0 && COL <cols && charStr [pathIndex] == Matrix [Row] [COL] && visited [Row * cols + COL] == to false ) { // corresponds // find next substring, and modify the access information pathIndex ++ ; visited [Row * cols + COL] = to true ; // from the four-direction position of the element to find the next string result = findPathCore (matrix, charStr, pathIndex, row + 1, col, rows, cols,visited) || findPathCore (Matrix, charStr, pathIndex, Row -. 1, COL, rows, cols, visited) || findPathCore (Matrix, charStr, pathIndex, Row, COL +. 1, rows, cols, visited) || findPathCore (Matrix, charStr, pathIndex, Row, COL -. 1 , rows, cols, visited); // four directions are no corresponding substring is found, it indicates that the location is not correct // modified access information, and then return to a position IF (! Result) { visited [Row * cols + COL] = to false ; } } return Result; } // the Test Output INPUT and public static void main(String[] args) { Solution solution = new Solution(); char[] char1 = {'a', 'b', 't', 'g'}; char[] char2 = {'c', 'f', 'c', 's'}; char[] char3 = {'j', 'd', 'e', 'h'}; char[] char4 = {'a', 'b', 't', 'g'}; char[][] chars = {char1, char2, char3, char4}; String str = "bfcc"; System.out.println(solution.findPath(chars, str)); } }