日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

LeetCode 79 Word Search(单词查找)

發布時間:2024/4/17 编程问答 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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(单词查找)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。