package com.wsy;
public class Main {
public static void main(String[] args) {
char[][] map = new char[][]{{'a', 'b', 't', 'g'}, {'c', 'f', 'c', 's'}, {'j', 'd', 'e', 'h'}};
char[] aim = new char[]{'b', 'f', 'c', 'e'};
boolean hasPath = hasPath(map, aim);
System.out.println(hasPath);
}
public static boolean hasPath(char[][] map, char[] aim) {
if (map == null) {
return false;
}
int rows = map.length;
int cols = map[0].length;
if (rows < 1 || cols < 1) {
return false;
}
int index = 0;
boolean[][] visit = new boolean[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (hasPathCore(map, i, j, aim, index, visit)) {
return true;
}
}
}
return false;
}
public static boolean hasPathCore(char[][] map, int row, int col, char[] aim, int index, boolean[][] visit) {
if (index == aim.length) {
return true;
}
int rows = map.length;
int cols = map[0].length;
boolean hasPath = false;
if (row >= 0 && col >= 0 && row < rows && col < cols && !visit[row][col] && map[row][col] == aim[index]) {
index++;
visit[row][col] = true;
hasPath = hasPathCore(map, row + 1, col, aim, index, visit) || hasPathCore(map, row - 1, col, aim, index, visit) || hasPathCore(map, row, col + 1, aim, index, visit) || hasPathCore(map, row, col - 1, aim, index, visit);
if (!hasPath) {
index--;
visit[row][col] = false;
}
}
return hasPath;
}
}