劍指offer 面試題12:回溯法,矩陣中的路徑 面試題13:機器人的運動範圍 java

Github 源碼地址

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

  • 解題思路:回溯法,使用遞歸。

要點:

1、定義row、column生成矩陣
2、先默認標記爲符合條件,然後遍歷4個方向,遞歸完成路徑深度遍歷,最後判斷條件不滿足時,將標記恢復

注意:

通常二維矩陣上查找路徑都可以通過回溯法解決

實現:

public class PathInMatrix {
    public static void main(String args[]) {
        char[] matrix = new char[]{'A', 'B', 'C', 'E', 'S', 'F', 'C', 'S', 'A', 'D', 'E', 'E'};
        char[] str = new char[]{'A', 'B', 'C', 'C', 'E', 'D'};
        System.out.println(hasPath(matrix, 3, 4, str));
    }

    public static boolean hasPath(char[] matrix, int rows, int clos, char[] str) {
        if (matrix == null || str == null || matrix.length < 1 || matrix.length < str.length) {
            return false;
        }
        boolean[] visited = new boolean[rows * clos];
        int curLength = 0;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < clos; j++) {
                return coreHasPath(matrix, rows, clos, i, j, str, visited, curLength);
            }
        }
        return false;
    }

    private static boolean coreHasPath(char[] matrix, int rows, int cols, int row, int col, char[] str, boolean[] visited, int curLength) {
        if (curLength == str.length) {
            return true;
        }

        boolean hasPath = false;
        if (row >= 0 && row < rows && col >= 0 && col < cols && !visited[row * cols + col] && matrix[row * cols + col] == str[curLength]) {
            curLength++;
            // 先默認標記爲符合條件
            visited[row * cols + col] = true;
            // 遍歷4個方向,遞歸完成路徑深度遍歷
            hasPath = coreHasPath(matrix, rows, cols, row - 1, col, str, visited, curLength) ||
                    coreHasPath(matrix, rows, cols, row + 1, col, str, visited, curLength) ||
                    coreHasPath(matrix, rows, cols, row, col - 1, str, visited, curLength) ||
                    coreHasPath(matrix, rows, cols, row, col + 1, str, visited, curLength);
            // 條件不滿足時,將標記恢復
            if (!hasPath) {
                visited[row * cols + col] = false;
            }

        }

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