1. 程式人生 > >劍指offer面試題12:矩陣中的路徑(Java 實現)

劍指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)開始迴圈,找出是否存在字串。