矩陣中的路徑(回溯法)

題目描述

請設計一個函數,用來判斷在一個矩陣中是否存在一條包含某字符串所有字符的路徑。路徑可以從矩陣中的任意一個格子開始,每一步可以在矩陣中向左,向右,向上,向下移動一個格子。如果一條路徑經過了矩陣中的某一個格子,則之後不能再次進入這個格子。 例如 a b c e s f c s a d e e 這樣的3 X 4 矩陣中包含一條字符串"bcced"的路徑,但是矩陣中不包含"abcb"路徑,因爲字符串的第一個字符b佔據了矩陣中的第一行第二個格子之後,路徑不能再次進入該格子。

 不用把字符串真的存進矩陣中,在字符數組中的位置和矩陣下標有對應關係

回溯:從矩陣的第一個字符開始找起,不成功,則到第二個字符

根據四個方向,查看有沒有路徑中的下一個字符,有則繼續以找打的那個位置按照不同的方向查找,沒有返回上一層,從不同的方向繼續查找

public class Solution {
	public boolean hasPath(char[] matrix, int rows, int cols, char[] str) {

		boolean visited[] = new boolean[matrix.length];
		for (int i = 0; i < rows; i++) {
			for (int j = 0; j < cols; j++) {
				if (hasPathHelper(matrix, rows, cols, i, j, 0, str, visited)) {
					return true;
				}
			}
		}
		return false;
	}

	public boolean hasPathHelper(char[] matrix, int rows, int cols, int row,
			int col, int index, char[] str, boolean[] visited) {

		if(col<0 || col>=cols || row<0 || row>=rows || 
				str[index]!=matrix[row*cols+col] || visited[row*cols+col]){
			return false;
		}
		if(index==str.length-1) return true;
		visited[row*cols+col] = true;
		if(hasPathHelper(matrix, rows, cols, row-1, col, index+1, str, visited)
		|| hasPathHelper(matrix, rows, cols, row+1, col, index+1, str, visited)
		|| hasPathHelper(matrix, rows, cols, row, col+1, index+1, str, visited)
		|| hasPathHelper(matrix, rows, cols, row, col-1, index+1, str, visited)){
			return true;
		}
		visited[row*cols+col] = false;
		return false;
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章