[leetCode]剑指 Offer 12. 矩阵中的路径
回溯法
回溯法适合由多个步骤组成的问题,并且每个步骤有多个选项。在某一步选择一个选项如果符合约束条件则进入下一步,如果不符合约束条件则回到上一步,就这样重复选择直至达到最终状态。
class Solution {
public boolean exist(char[][] board, String word) {
if(board == null || word == null || board.length == 0){
return false;
}
int rows = board.length;
int cols = board[0].length;
//创建一个辅助矩阵,用于标识路径是否已经进入过格子
boolean[][] visited = new boolean[rows][cols];
int pathLengh = 0;
//对矩阵每个元素进行查询
for(int row = 0; row < rows; row++){
for(int col = 0; col < cols; col++){
if(hasPathCore(board,visited,row,col,pathLengh,word,rows,cols)){
return true;
}
}
}
return false;
}
private boolean hasPathCore(char[][] board,boolean[][] visited,
int row, int col,
int pathLengh, String word,
int rows, int cols) {
if(pathLengh == word.length())
return true;
boolean hasPath = false;
if(row >= 0 && row < rows && col >= 0 && col< cols
&& board[row][col] == word.charAt(pathLengh) && !visited[row][col]){
++pathLengh;
visited[row][col] = true;
hasPath = hasPathCore(board,visited,row-1,col,pathLengh,word,rows,cols)||
hasPathCore(board,visited,row+1,col,pathLengh,word,rows,cols)||
hasPathCore(board,visited,row,col-1,pathLengh,word,rows,cols)||
hasPathCore(board,visited,row,col+1,pathLengh,word,rows,cols);
if(!hasPath){
--pathLengh;
visited[row][col] = false;
}
}
return hasPath;
}
}