import java.util.*; public class Solution { ArrayList<Integer> isvisited = new ArrayList<Integer>(); public boolean hasPath(char[] matrix, int rows, int cols, char[] str) { boolean flag = false; for (int i = 0; i < matrix.length; i++) { if (matrix[i] == str[0]) { flag = flag || hasPath2(matrix, rows, cols, str, i, 0); } } return flag; } public boolean hasPath2(char[] matrix, int rows, int cols, char[] str, int start, int index) { boolean flag1 = false, flag2 = false, flag3 = false, flag4 = false; isvisited.add(start); if (index == str.length - 1) return true; int u = up(rows, cols, start); if (u != -1 && matrix[u] == str[index + 1]) flag1 = hasPath2(matrix, rows, cols, str, u, index + 1); int d = down(rows, cols, start); if (d != -1 && matrix[d] == str[index + 1]) flag2 = hasPath2(matrix, rows, cols, str, d, index + 1); int l = left(rows, cols, start); if (l != -1 && matrix[l] == str[index + 1]) flag3 = hasPath2(matrix, rows, cols, str, l, index + 1); int r = right(rows, cols, start); if (r != -1 && matrix[r] == str[index + 1]) flag4 = hasPath2(matrix, rows, cols, str, r, index + 1); isvisited.remove(isvisited.size() - 1); return flag1 || flag2 || flag3 || flag4; } public int up(int rows, int cols, int start) { int tmp = start - cols; if (tmp < 0 || tmp >= rows * cols || isvisited.contains(tmp)) return -1; return tmp; } public int down(int rows, int cols, int start) { int tmp = start + cols; if (tmp < 0 || tmp >= rows * cols || isvisited.contains(tmp)) return -1; return tmp; } public int left(int rows, int cols, int start) { int tmp = start - 1; if (tmp < 0 || tmp >= rows * cols || isvisited.contains(tmp)) return -1; return tmp; } public int right(int rows, int cols, int start) { int tmp = start + 1; if (tmp < 0 || tmp >= rows * cols || isvisited.contains(tmp)) return -1; return tmp; } }