剑指 Offer 12. 矩阵中的路径
给定一个 m x n 二维字符网格 board 和一个字符串单词 word 。如果 word 存在于网格中,返回 true ;否则,返回 false 。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
例如,在下面的 3×4 的矩阵中包含单词 "ABCCED"(单词中的字母已标出)。
示例 1:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
输出:true
示例 2:
输入:board = [["a","b"],["c","d"]], word = "abcd"
输出:false
思路:考虑使用回溯,对每个坐标暴力穷举。但是很明显,如果使用回溯会走回头路,考虑走过的路用’\0’空字符来代替,这样匹配回头路的时候一定会失败,从而避免了走回头路;
class Solution {
public boolean exist(char[][] board, String word) {
// 字符串转字符数组
char[] words = word.toCharArray();
// 暴力穷举 每个回溯的情况
for(int row = 0; row < board.length; row++){
for(int column = 0; column < board[0].length;column++){
if(backTrace(board,words,row,column,0)){
return true;
}
}
}
// 都不符合 就返回false
return false;
}
// i -- 行 j -- 列 index -- 匹配字符串的索引
public boolean backTrace(char[][] board,char[] words,int i,int j,int index){
// 索引越界 或者 字符不匹配 直接返回false
if(i < 0 || i >=board.length || j < 0 || j >= board[0].length || board[i][j] != words[index]){
return false;
}
// 能到这,说明字符匹配成功
// 若长度一样 说明匹配成功
if(index == words.length-1) return true;
// 做选择,用空字符串 避免走回头路
board[i][j] = '\0';
// 回溯,上下左右,有一条路成功即可
boolean res = backTrace(board,words,i+1,j,index+1) || backTrace(board,words,i-1,j,index+1) || backTrace(board,words,i,j+1,index+1) || backTrace(board,words,i,j-1,index+1);
// 撤销选择
board[i][j] = words[index];
return res;
}
}