LeetCode 79. 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 =

[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]
word =  "ABCCED", -> returns  true,
word =  "SEE", -> returns  true,
word =  "ABCB", -> returns  false.

 


題目標簽:Array

 

  前兩天都沒有刷題,都在總結反省找工作失敗的原因。因為現在租的房子也快到期了,就開始尋覓新的居所。突然之間,在昨天看完家附近的一個apartment之后,想到,既然也要搬家,為何不搬去一個更適合找工作,而且房租更便宜的地方呢! (主要還是因為窮!)回到家之后,調查研究一天,決定了!准備搬家到其他州,畢竟現在居住的地方(紐約長島),不是非常適合new grad 找工作(主要是自己也不是大神,競爭不過別人)而且消費又高。巧的是,昨天雖然沒刷題,但是上來看了一眼visits記錄,發現居然有一個新的美國地區訪問,就是我要去的地方(德州),這也算是緣分吧,閑話就扯到這里,開始繼續說題。
 
  這道題目給了我們一個矩陣,讓我們找到矩陣中是否存在一個word,但是這個word是需要左右上下連起來的。換一種說法,就是在這個board上走path, 能不能找到這個word的path。一般題目做多了,這種要探究所有可能性的,特別是要倒退回來繼續探索其他方向的,基本大多都是backtracking。那么我們要走path,首先要找到起點,先遍歷board,把和word的第一個字母一樣的都當作起點代入我們的遞歸function。我們要記錄每一個點的position,所以要row 和col;我們要記錄word中的character,所以要一個wordIndex;最重要的是,我們需要判斷,哪些點我們已經走過了,所以要一個boolean markBoard[][];對於起點(每一個點),最基本的思路是,可以走四個方向,把那個方向的下一個點繼續遞歸,只要有一條path 成功了,返回回來就可以直接return了,不需要繼續把所有的pathes 都看完;對於每一個點,要檢查base case 1, word 是否已經找到了 return true; 還要檢查base case 2,這個點是否可以探索(比如這個點超出board范圍了,它和word中的char不相等,它已經被探索過了), return false。
 
 
 

Java Solution:

Runtime beats 34.54% 

完成日期:07/27/2017

關鍵詞:Array

關鍵點:Braktracking;新矩陣記錄探索過的點;每個點有4個方向可以探索

 

 

 1 public class Solution 
 2 {
 3     public boolean exist(char[][] board, String word) 
 4     {
 5         if(board == null || board.length == 0 
 6                 || board.length * board[0].length < word.length())
 7             return false;
 8         
 9         boolean[][] mark = new boolean[board.length][board[0].length];
10         boolean res = false;
11         // iterate board, find the match starting character to pass to findWord function
12         for(int i=0; i<board.length; i++)
13         {
14             for(int j=0; j<board[0].length; j++)
15             {
16                 if(board[i][j] == word.charAt(0))
17                     res = res || findWord(board, word, 0, i, j, mark);
18                 
19                 if(res)
20                     return res;
21             }
22         }
23         
24         return res;
25     }
26     
27     public boolean findWord(char[][] board, String word, int wordIndex, 
28             int row, int col, boolean[][] markBoard)
29     {
30         // base case 1: if exceed word's length, meaning it is done and found the word
31         if(wordIndex == word.length())
32             return true;
33         
34         /* base case 2: if this character is out of bound or 
35          * this character is not match to word's character or 
36          * hits character has been already visited
37             */
38         if(row >= board.length || row < 0 ||  col >= board[0].length || col < 0
39                 || word.charAt(wordIndex) != board[row][col] || markBoard[row][col])
40             return false;
41         
42         
43         // mark this char as visited 
44         markBoard[row][col] = true;
45         
46         // follow top, right, bottom, left order to check character
47         // if any direction future path return true, meaning no need to continue other directions
48         if(findWord(board, word, wordIndex + 1, row - 1, col, markBoard) || // go top
49            findWord(board, word, wordIndex + 1, row, col + 1, markBoard) || // go right
50            findWord(board, word, wordIndex + 1, row + 1, col, markBoard) || // go bottom:
51            findWord(board, word, wordIndex + 1, row, col - 1, markBoard))   // go left:
52         {
53             return true;
54         }
55         
56         markBoard[row][col] = false; // clear the mark of this character
57 
58         // if this this character's all four directions path has failed, return false to last level
59         return false;
60     }
61 }

參考資料:N/A

 

LeetCode 算法題目列表 - LeetCode Algorithms Questions List

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM