[LeetCode][Java] Word Search

來源:互聯網
上載者:User

標籤: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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.