剑指 Offer 12. 矩阵中的路径

2021-03-09  本文已影响0人  7ccc099f4608

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;
    }
上一篇下一篇

猜你喜欢

热点阅读