標籤:leetcode java word search
題目:
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
For example,
Given board =
[ ["ABCE"], ["SFCS"], ["ADEE"]]
word =
"ABCCED", -> returns
true,
word =
"SEE", -> returns
true,
word =
"ABCB", -> returns
false.
題意:
給定一個二維的模板,在格子中尋找一個單詞,看其是否存在。
這個單詞是由格子中的相鄰的緊挨的水平或者豎直方向的元素構成的。同一個字母元素只能被使用一次。
For example,
Given board =
[ ["ABCE"], ["SFCS"], ["ADEE"]]
word =
"ABCCED", -> returns
true,
word =
"SEE", -> returns
true,
word =
"ABCB", -> returns
false.
演算法分析:
參考部落格http://blog.csdn.net/linhuanmars/article/details/24336987
這道題很容易感覺出來是圖的題目,其實本質上還是做深度優先搜尋。基本思路就是從某一個元素出發,往上下左右深度搜尋是否有相等於word的字串。這裡注意每次從一個元素出發時要重設訪問標記(也就是說雖然單次搜尋字元不能重複使用,但是每次從一個新的元素出發,字元還是重新可以用的)。深度優先搜尋的演算法就不再重複解釋了,不瞭解的朋友可以看看wiki - 深度優先搜尋。我們知道一次搜尋的複雜度是O(E+V),E是邊的數量,V是頂點數量,在這個問題中他們都是O(m*n)量級的(因為一個頂點有固定上下左右四條邊)。加上我們對每個頂點都要做一次搜尋,所以總的時間複雜度最壞是O(m^2*n^2),空間上就是要用一個數組來記錄訪問情況,所以是O(m*n)。
AC代碼:
<span style="font-family:Microsoft YaHei;font-size:12px;">public class Solution {public boolean exist(char[][] board, String word) { if(word==null || word.length()==0) return true; if(board==null || board.length==0 || board[0].length==0) return false; boolean[][] used = new boolean[board.length][board[0].length]; for(int i=0;i<board.length;i++) { for(int j=0;j<board[0].length;j++) { if(search(board,word,0,i,j,used)) return true; } } return false;}private boolean search(char[][] board, String word, int index, int i, int j, boolean[][] used){ if(index == word.length()) return true; if(i<0 || j<0 || i>=board.length || j>=board[0].length || used[i][j] || board[i][j]!=word.charAt(index)) return false; used[i][j] = true; boolean res = search(board,word,index+1,i-1,j,used) || search(board,word,index+1,i+1,j,used) || search(board,word,index+1,i,j-1,used) || search(board,word,index+1,i,j+1,used); used[i][j] = false; return res;}}</span>
著作權聲明:本文為博主原創文章,轉載註明出處
[LeetCode][Java] Word Search