image.pnghttps://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof/
(图片来源https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof/
)
日期 | 是否一次通过 | comment |
---|---|---|
2021-03-07 | 0 |
回溯
for不放在dfs里:
- 状态数确定,就是两个for(不像subset,状态不确定);
- 会走回头路,允许往回走([["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;
}
网友评论