参考资料:左程云算法课
79. Word Search
Given an m x n grid of characters board and a string word, return true if word exists in the grid.
The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
Example 1:
Input: board =
[[“A”,“B”,“C”,“E”],
[“S”,“F”,“C”,“S”],
[“A”,“D”,“E”,“E”]], word = “ABCCED”
Output: true
思路:主函数中枚举路径的起点board[i][j],从str[0]开始匹配str。只有有一个成功,就返回true.
设计递归函数检查从board[i][j]开始能够配出str[index…]。
注意:为了防止”走重复路“,应该给走过的点做上标记,尝试完四个方向之后记得恢复现场。(深度优先遍历)
“走重复路”的例子
board =
A B
D C
A
str = “ABCDA”
如果不给最左上角的A做上标记,那么等走到D时,有可能再次回到 最左上角的A, 即 “走重复路”,不符合题意。
public boolean exist(char[][] board, String s){int n= board.length;int m = board[0].length;char[] str = s.toCharArray();for(int i=0;i<n;i++){for(int j=0;j<m;j++){if(f(board,i,j,str,0)){return true;}}}return false;// f(i,j,board,str,index) // start from [i][j] to match str[index..]}public boolean f(char[][] board,int i, int j, char[] str, int index){if(str.length==index) // !! 这个判断一定要放在下面这个判断的前面,否则会报错,超出索引上界{return true;}if(i<0||i>=board.length||j<0||j>=board[0].length||board[i][j]!=str[index]){return false;}board[i][j]='.';boolean b1 = f(board,i-1,j,str,index+1);boolean b2 = f(board,i,j-1,str, index+1);boolean b3 = f(board,i,j+1,str, index+1);boolean b4 = f(board,i+1,j,str, index+1);board[i][j] = str[index];return b1||b2||b3||b4;}