LeetCode Word Search

原题链接在这里:https://leetcode.com/problems/word-search/

这是典型的递归加回朔,与N-Queens一个套路,先往前走,若是能走到index == word.length() 返回true, res就记为true; 若是做不到就是中间出现了越界或者不等,返回false 给res.

用之前要把used 对应位置改为true, 用完后记得把used 对应位置改为false. 

最后返回res.

Time Complexity: O(m^2 * n^2).  对于board每一个点search都是一次dfs, dfs用了O(V+E), 矩阵表示时就是O(m*n). 并且board一共有m*n个点.

Space: O(m*n). 因为用了used存储。这里m=board.length, n = board[0].length.

AC Java:

 1 public class Solution {
 2     public boolean exist(char[][] board, String word) {
 3     if(word==null || word.length()==0)  
 4         return true;  
 5     if(board==null || board.length==0 || board[0].length==0)  
 6         return false;  
 7     boolean[][] used = new boolean[board.length][board[0].length];  
 8     for(int i=0;i<board.length;i++)  
 9     {  
10         for(int j=0;j<board[0].length;j++)  
11         {  
12             if(search(board,word,0,i,j,used))  
13                 return true;  
14         }  
15     }  
16     return false;  
17 }  
18 private boolean search(char[][] board, String word, int index, int i, int j, boolean[][] used)  
19 {  
20     if(index == word.length())  
21         return true;  
22     if(i<0 || j<0 || i>=board.length || j>=board[0].length || used[i][j] || board[i][j]!=word.charAt(index))  
23         return false;  
24     used[i][j] = true;  
25     boolean res = search(board,word,index+1,i-1,j,used)   
26                 || search(board,word,index+1,i+1,j,used)  
27                 || search(board,word,index+1,i,j-1,used)   
28                 || search(board,word,index+1,i,j+1,used);  
29     used[i][j] = false;  
30     return res;  
31     }
32 }

 

你可能感兴趣的:(LeetCode Word Search)