剑指 Offer 12. 矩阵中的路径-回溯法

回溯法的经典题目,不解释了

public class Solution {
    /**
     * @see <a href="https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof/">剑指 Offer 12. 矩阵中的路径</a>
     *
     * @param board 矩阵
     * @param word  字符串
     * @return  是否存在路径
     */
    public boolean exist(char[][] board, String word) {
        // 判空
        if (board == null || board.length == 0 || board[0] == null || board[0].length == 0 || word == null || word.length() == 0) return false;
        boolean[][] isVisited = new boolean[board.length][board[0].length];
        char[] charArray = word.toCharArray();

        // 顺序遍历,如果从某个位置开始深度搜索能够找到路径则返回
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (backtrack(board, i, j, isVisited, charArray, 0)) return true;
            }
        }
        return false;
    }

    /**
     * 从i,j开始寻找完整路径
     *
     * @param board 矩阵
     * @param i 坐标i
     * @param j 坐标j
     * @param isVisited 已遍历矩阵
     * @param charArray 字符数组
     * @param index 字符索引
     * @return  是否存在路径
     */
    private boolean backtrack(char[][] board, int i, int j, boolean[][] isVisited, char[] charArray, int index) {
        // 遍历到最后一个字符
        if (index == charArray.length) return true;
        if (i < 0 || j < 0 || i == board.length || j == board[0].length || isVisited[i][j] || board[i][j] != charArray[index]) return false;

        // 回溯
        isVisited[i][j] = true;

        if (backtrack(board, i, j - 1, isVisited, charArray, index + 1) ||
                backtrack(board, i, j + 1, isVisited, charArray, index + 1) ||
                backtrack(board, i - 1, j, isVisited, charArray, index + 1) ||
                backtrack(board, i + 1, j, isVisited, charArray, index + 1)) return true;

        isVisited[i][j] = false;

        return false;
    }
}

上一篇:基于java的学生学籍管理系统(含源文件)


下一篇:Array sort