Sword refers to offer 12. The path in the matrix
Title description
Problem-solving ideas
This problem is backtracking, by board[row][col] = '#';
choice, and deselection after traversing the four directions, can prevent repeat visits of the current element , acts visited the array.
Note the difference between this question and Sword Finger Offer 13. The robot's range of motion . Why is there only one question visited[row][col] = true;
, and there is no need to revoke this choice?
Because this problem needs to find a path, an element can appear on multiple paths , so after visiting a path, you need to backtrack to clear the visited array (that is, to cancel the selection), and continue to visit the next path, that is, the idea of backtracking. The 13th question is that as long as one location has been visited, it is marked as visited, and the whole process cannot be visited again.
class Solution {
public boolean exist(char[][] board, String word) {
char[] words = word.toCharArray();
int rowNum = board.length, colNum = board[0].length;
for (int row = 0; row < rowNum; row++) {
for (int col = 0; col < colNum; col++) {
//剪枝,找到一个满足条件,则直接返回
if (backtrack(board, row, col, words, 0)) return true;
}
}
return false;
}
//定义:从board[row][col]开始的四个方向,能否找到匹配目标字符串的下一个方向
boolean backtrack(char[][] board, int row, int col, char[] words, int idx) {
//行列越界,或者和board[row][col]当前字符不一致,或者已经访问过
if (row < 0 || row >= board.length || col < 0 || col >= board[0].length || words[idx] != board[row][col])
return false;
//如果能一直匹配到words末尾,则返回true
if (idx == words.length - 1)
return true;
//回溯,防止重复访问
board[row][col] = '#';
boolean res = backtrack(board, row + 1, col, words, idx + 1)
|| backtrack(board, row - 1, col, words, idx + 1)
|| backtrack(board, row, col + 1, words, idx + 1)
|| backtrack(board, row, col - 1, words, idx + 1);
board[row][col] = words[idx];
return res;
}
}