剑指offer面试题12:矩阵中的路径(Java 实现)

题目:请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有的路径。路径可以从矩阵中的任意一格开始,每一步可以在矩阵中向左,右,上,下移动一格。如果有一条路径经过了矩阵的某一格,那么该路径不能在此进入该格子,例如,在下面的3x4的矩阵中包含一条字符串"bfce"的路径(路径中的字母用下划线标出)。但矩阵中不包含字符串‘abfb“路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入这个格子。

撸上代码;

public class Solution {
    public boolean hasPath(char[] matrix, int rows, int cols, char[] str) {
        if(matrix.length<=0||rows<=0||cols<=0||str.length<=0)
            return false;
		boolean[] flag = new boolean[matrix.length];
		for (int i = 0; i < rows; i++) {
			for (int j = 0; j < cols; j++) {
				if (isInclude(matrix, rows, cols, i, j, 0, str, flag)) {
					return true;
				}
			}
		}
		return false;
	}

	static boolean isInclude(char[] matrix, int rows, int cols, int row, int col, int index, char[] str, boolean[] flag) {
		if (row < 0 || row >= rows || col < 0 || col >= cols || flag[row * cols + col] == true
				|| matrix[row * cols + col] != str[index])
			return false;
		if (index == str.length - 1)
			return true;
		flag[row * cols + col] = true;
		if (isInclude(matrix, rows, cols, row - 1, col, index + 1, str, flag)
				|| isInclude(matrix, rows, cols, row + 1, col, index + 1, str, flag)
				|| isInclude(matrix, rows, cols, row, col - 1, index + 1, str, flag)
				|| isInclude(matrix, rows, cols, row, col + 1, index + 1, str, flag)) {
			return true;
		}
		flag[row*cols+col] = false;
		return false;
	}
}

分析:1)我们先对数据进行正确与否判断。

2)创建flag标志数组进行标志该格子是否被访问过。

3)开始循环,找出是否存在字符串。

猜你喜欢

转载自blog.csdn.net/qq_40931405/article/details/83045216