LeetCode 79 Word Search(单词查找)
題目鏈接:https://leetcode.com/problems/word-search/#/description
?
給出一個二維字符表,并給出一個String類型的單詞,查找該單詞是否出現在該二維字符表中。
?
For example,
Given?board?=
?
[['A','B','C','E'],['S','F','C','S'],['A','D','E','E'] ]word?=?"ABCCED", -> returns?true,
word?=?"SEE", -> returns?true,
word?=?"ABCB", -> returns?false.
?
?
同樣還是使用第78題的方法,也就是回溯法求解。
通過上述例子,每次都是只能查找當前位置的上下左右四個位置(最多是四個位置,還有邊界情況)。當查找到該單詞的某個位置時,通過計數器不斷更新當前已經匹配的字符的個數。
通過移動查找的坐標(row,col)來進行對一棵樹的深度遍歷操作。也就是dfs遍歷操作。
調用dfs遍歷的循環是有兩層的。每次當遍歷的一棵子樹到葉子節點時,重新進入原始的循環體。更新樹的遍歷根節點。
因此循環體為
for(int i = 0 ; i < row ; i++){for(int j = 0 ; j < col ; j++){dfs();// calling the function to go through the tree}}
?
需要考慮遞歸函數的出口問題:因為需要對單詞中的每個字符進行匹配操作,所以設置計數器用來統計當前所匹配的字符個數,同時也可以使用該變量來得到接下來要匹配的單詞的字符。
如果給計數器個數等于單詞的長度時,說明單詞的所有字符都可以在表中找到,此時返回結果為true
如果當前的位置上下左右四個cell都不能與單詞的字符進行匹配時,此時遞歸函數應退出并放回結果為false;
?
?
上面考慮了遞歸函數的出口問題,下面是對整個問題的結果進行討論。
當有一個位置能夠查找到目標單詞的所有字符時就應該返回true,
當遍歷開始位置從(0,0)到(board.row, board.col)結束都沒有查找到時,返回false;
?
根據上述分析,得到以下參考代碼:
package leetcode_100;/**** * @author pengfei_zheng* 二維字符表中查找單詞*/ public class Solution79 {public static boolean exist(char[][] board, String word) {int row = board.length;int col = board[0].length;boolean[][] visited = new boolean[row][col];//record whether this cell is visitedfor(int i=0;i<row;i++)for(int j=0;j<col;j++)if(dfs(board,visited,i,j,0,word))// calling the function to check word return true;//if this start position(i,j) can match the word then just return truereturn false;//if all the position can't match the word then return false }private static boolean dfs(char[][] board, boolean[][] visited, int row, int col, int index, String word) {if(word.length() == index){//judge whether match the wordreturn true;}if(row<0 || col<0|| row>=board.length || col>=board[0].length) return false;//considering the boundarychar ch = word.charAt(index);//get next Characterif(!visited[row][col] && ch == board[row][col]){// this position can match the Charactervisited[row][col] = true;//calling itself going through the tree//four conditions: up && down && left && rightboolean res = dfs(board,visited,row-1,col,index+1,word)|| dfs(board,visited,row+1,col,index+1,word)||dfs(board,visited,row,col-1,index+1,word)|| dfs(board,visited,row,col+1,index+1,word);visited[row][col] = false;return res;}return false;//not found } }?
?
?
轉載于:https://www.cnblogs.com/zpfbuaa/p/6634147.html
總結
以上是生活随笔為你收集整理的LeetCode 79 Word Search(单词查找)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Problem H: tmk买礼物
- 下一篇: CF617E. XOR and Favo