演算法題(二十一):回溯法解決矩陣路徑問題
阿新 • • 發佈:2018-11-21
題目描述
請設計一個函式,用來判斷在一個矩陣中是否存在一條包含某字串所有字元的路徑。路徑可以從矩陣中的任意一個格子開始,每一步可以在矩陣中向左,向右,向上,向下移動一個格子。如果一條路徑經過了矩陣中的某一個格子,則之後不能再次進入這個格子。 例如 a b c e s f c s a d e e 這樣的3 X 4 矩陣中包含一條字串"bcced"的路徑,但是矩陣中不包含"abcb"路徑,因為字串的第一個字元b佔據了矩陣中的第一行第二個格子之後,路徑不能再次進入該格子。
分析
從任意一點開始搜尋,設定一個boolean陣列或(0,1)陣列,記錄一趟搜尋過程中已經訪問過的位置(設定為true或1)。對每個位置的上下左右進行判斷,並進行遞迴訪問,直到找到路徑,或不滿足條件而終止。當不滿足條件而終止時,程式返回到上一位置,並對未訪問的方向進行訪問。
程式碼
public class MatrixPath { public static void main(String[] args) { // TODO Auto-generated method stub char[] matrix = "abcesfcsadee".toCharArray(); char[] strs = "abcced".toCharArray(); int rows = 3; int cols = 4; MatrixPath m = new MatrixPath(); System.out.println(m.hasPath(matrix, rows, cols, strs)); } public boolean hasPath(char[] matrix, int rows, int cols, char[] str) { int flag[] = new int[matrix.length]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (helper(matrix, rows, cols, i, j, str, 0, flag)) return true; } } return false; } private boolean helper(char[] matrix, int rows, int cols, int i, int j, char[] str, int k, int[] flag) { int index = i * cols + j; if (i < 0 || i >= rows || j < 0 || j >= cols || matrix[index] != str[k] || flag[index] == 1) return false; if(k == str.length - 1) return true; flag[index] = 1; if (helper(matrix, rows, cols, i - 1, j, str, k + 1, flag) || helper(matrix, rows, cols, i + 1, j, str, k + 1, flag) || helper(matrix, rows, cols, i, j - 1, str, k + 1, flag) || helper(matrix, rows, cols, i, j + 1, str, k + 1, flag)) { return true; } flag[index] = 0; return false; } }