题目:请设计一个函数,用来判断矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中任意一格开始,每一步可以上下左右移动一格,但不允许经过已经经过的格子。例如,在下面的3*4矩阵中含有“bfce”的路径,但不包含“abfb”的路径,矩阵如下:
a b t g
c f c s
j d e h
思路:采用回溯法,遍历所有格子,例如从格子一进去时判断格子一的元素是否等于路径的第一个元素,不等就跳出遍历下一个,等于就进入下一步,下一步有可能上下左右,先上的话,进入格子二,判断是否等于路径第二个元素,等于就继续深入,不等于就返回格子一,再向下尝试,直到把上下左右都尝试遍了,若没有可行的路径,就从其他元素开始走起。
解法:
public class Test1 {
public static void main(String[] args) {
char[][] chars = { { 'a', 'b', 't', 'g' }, { 'c', 'f', 'c', 's' }, { 'j', 'd', 'e', 'h' } };
// char[] str = { 'b', 'f', 'c', 'e' };
// char[] str = { 'a', 'b', 'f', 'b' };
char[] str = { 'a', 'b', 'f', 'c' };
boolean b = findStr(chars, 3, 4, str);
if (b) {
System.out.println("矩阵中含有该字符串");
} else {
System.out.println("矩阵中没有该字符串");
}
}
private static boolean findStr(char[][] chars, int row, int col, char[] str) {
if (chars == null || row < 1 || col < 1 || str == null) {
return false;
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
int pathLength = 0;// 记录已经走过的路径
boolean[][] flags = new boolean[row][col];
if (hasPath(chars, row, col, str, i, j, flags, pathLength)) {
return true;
}
}
}
return false;
}
private static boolean hasPath(char[][] chars, int row, int col, char[] str, int i, int j, boolean[][] flags,
int pathLength) {
boolean bb = false;
if (i >= 0 && i < row && j >= 0 && j < col && chars[i][j] == str[pathLength] && !flags[i][j]) {
if ((pathLength == (str.length - 1)) && str[pathLength] == chars[i][j]) {
return true;
}
pathLength++;
flags[i][j] = true;
bb = hasPath(chars, row, col, str, i + 1, j, flags, pathLength)
|| hasPath(chars, row, col, str, i - 1, j, flags, pathLength)
|| hasPath(chars, row, col, str, i, j + 1, flags, pathLength)
|| hasPath(chars, row, col, str, i, j - 1, flags, pathLength);
if(!bb){
--pathLength;
flags[i][j]=false;
}
}
return bb;
}
}
有帮助到你的话点个赞哦^-^