题目
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一格开始,每一步可以在矩阵中向左、右、上、下移动一格。如果一条路径经过了矩阵的某一格,那么该路径不能再次进入该格子。例如,在下面的3×4的矩阵中包含一条字符串“bfce”的路径(路径中的字母用加粗标出)。
[[“a”,“b”,“c”,“e”],
[“s”,“f”,“c”,“s”],
[“a”,“d”,“e”,“e”]]
但矩阵中不包含字符串“abfb”的路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入这个格子。
代码
import java.util.LinkedList;
import java.util.Objects;
import java.util.Scanner;
/**
* @author 申劭明
* @date 2020/9/17 16:06
*/
public class Main {
/**
* 用于记录走过的路
*/
private final LinkedList<PassWay> passes = new LinkedList<>();
private final char[][] chars;
private final char[] targetChars;
private final int targetLen;
private final int rowLen;
private final int colLen;
public Main(char[][] chars, char[] targetChars) {
this.chars = chars;
this.targetChars = targetChars;
this.targetLen = targetChars.length;
this.rowLen = chars.length;
this.colLen = chars[0].length;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
scanner.nextLine();
char[][] chars = new char[n][m];
String targetWord = scanner.nextLine();
for (int i = 0