美文网首页
剑指 Offer 12. 矩阵中的路径

剑指 Offer 12. 矩阵中的路径

作者: 7ccc099f4608 | 来源:发表于2021-03-09 09:51 被阅读0次

    https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof/

    image.png

    (图片来源https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof/

    日期 是否一次通过 comment
    2021-03-07 0

    回溯

    for不放在dfs里:

    1. 状态数确定,就是两个for(不像subset,状态不确定);
    2. 会走回头路,允许往回走([["a","b"]],"ba",输出的结果是true)

    public boolean exist(char[][] board, String word) {
            if(board == null || board.length < 1 || board[0].length < 1 || word.isEmpty()) {
                return false;
            }
    
            for(int i=0; i<board.length; i++) {
                for(int j=0; j<board[0].length; j++) {
                    if(helper(board, word, i, j, 0)) {
                        return true;
                    }
                }
            }
            return false;
    
        }
    
        private boolean helper(char[][] board, String word, int i, int j, int wdIdx) {
            if(i < 0 || i >= board.length || j < 0 || j >= board[0].length) {
                return false;
            }
    
            if(word.charAt(wdIdx) != board[i][j]) {
                return false;
            }
    
            if(wdIdx == word.length()-1) {
                return true;
            }
    
            board[i][j] = '\0';
            boolean res = helper(board, word, i+1, j, wdIdx+1) ||  helper(board, word, i-1, j, wdIdx+1) 
                        ||  helper(board, word, i, j+1, wdIdx+1) ||  helper(board, word, i, j-1, wdIdx+1);
    
            board[i][j] = word.charAt(wdIdx);  // 回溯恢复上一个状态
    
            return res;
        }

    相关文章

      网友评论

          本文标题:剑指 Offer 12. 矩阵中的路径

          本文链接:https://www.haomeiwen.com/subject/ybbuqltx.html