5、矩阵中的路径

矩阵中的路径:

题目:

5、矩阵中的路径

实现:

代码实现
public class Solutionm {
    // 矩阵中的路径
    public boolean exist(char[][] board, String word) {
        char[] charArr = word.toCharArray();
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (dfs(board, charArr, i, j, 0)) {
                    return true;
                }
            }
        }

        return false;
    }


    public boolean dfs(char[][] board, char[] word, int i, int j, int k) {
        if (i > board.length || i < 0 || j > board[0].length || j < 0 || board[i][j] != word[k]) {
            return false;
        }

        if (k == word.length - 1) {
            return true;
        }

        board[i][j] = '\0';

        boolean res = dfs(board, word, i + 1, j, k + 1) || dfs(board, word, i - 1, j, k + 1) ||
                dfs(board, word, i, j + 1, k + 1) || dfs(board, word, i, j - 1, k + 1);
        board[i][j] = word[k];

        return res;
    }
}
上一篇:Pytest单元测试框架生成HTML测试报告及优化


下一篇:python测试框架之pytest (三)断言