写法值得借鉴,每次没有匹配到的话对原来的矩阵有一个还原操作。
代码来源:
https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof/solution/mian-shi-ti-12-ju-zhen-zhong-de-lu-jing-shen-du-yo/
public boolean exist(char[][] board, String word) {
char[] arr = word.toCharArray();
for(int i = 0;i < board.length;i++){
for(int j = 0;j < board[0].length;j++){
if (isMatched(board,i,j,arr,0))return true;
}
}
return false;
}
private boolean isMatched(char[][] board, int i, int j,char[] arr,int k) {
if (i < 0 || j < 0 || i >= board.length || j >= board[0].length || arr[k] != board[i][j]) return false;
if (k == arr.length - 1) return true;
char temp = board[i][j];
board[i][j] = '/';
boolean res = (isMatched(board,i + 1,j,arr,k + 1) || isMatched(board,i,j + 1,arr,k + 1)||
isMatched(board,i - 1,j,arr,k + 1) || isMatched(board,i,j - 1,arr,k + 1));
board[i][j] = temp;
return res;
}