1. 程式人生 > 實用技巧 >LeetCode 單詞搜尋

LeetCode 單詞搜尋

給定一個二維網格和一個單詞,找出該單詞是否存在於網格中。

單詞必須按照字母順序,通過相鄰的單元格內的字母構成,其中“相鄰”單元格是那些水平相鄰或垂直相鄰的單元格。同一個單元格內的字母不允許被重複使用。

示例:

board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]

給定 word = "ABCCED", 返回 true
給定 word = "SEE", 返回 true
給定 word = "ABCB", 返回 false

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/word-search

著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

class Solution {
public:
 bool flag=false;
bool dfs(vector<vector<char>>& board, string &word,int rindex,int sindex,int cindex){
   
     if(rindex>=board.size()||rindex<0||cindex>=board[rindex].size()||cindex<0||board[rindex][cindex]!=word[sindex]){
         return false;
     }

    if(sindex==word.size()-1&&board[rindex][cindex]==word[sindex]){
         
         return true;
     }
            board[rindex][cindex]='.';
           flag= (dfs(board,word,rindex-1,sindex+1,cindex)||
            dfs(board,word,rindex+1,sindex+1,cindex)||
            dfs(board,word,rindex,sindex+1,cindex-1)||
            dfs(board,word,rindex,sindex+1,cindex+1)); 
            board[rindex][cindex]=word[sindex];
            return flag;
 }
    bool exist(vector<vector<char>>& board, string word) {
        for(int i=0;i<board.size();i++){
            for(int j=0;j<board[i].size();j++){
                
                if(dfs(board,word,i,0,j)){
                    return true;
                };
            }
        }
       return false;
    }
};


第二段(超出時間限制):
class Solution {
public:
 bool flag=false;
void dfs(vector<vector<char>>& board, string &word,int rindex,int sindex,int cindex){
   
     if(rindex>=board.size()||rindex<0||cindex>=board[rindex].size()||cindex<0||board[rindex][cindex]!=word[sindex]){
         return;
     }

    if(sindex==word.size()-1&&board[rindex][cindex]==word[sindex]){
         flag=true;
         return ;
     }
      
            board[rindex][cindex]='.';
            dfs(board,word,rindex-1,sindex+1,cindex);
            dfs(board,word,rindex+1,sindex+1,cindex);
            dfs(board,word,rindex,sindex+1,cindex-1);
            dfs(board,word,rindex,sindex+1,cindex+1);  
      board[rindex][cindex]=word[sindex];
 }
    bool exist(vector<vector<char>>& board, string word) {
        for(int i=0;i<board.size();i++){
            for(int j=0;j<board[i].size();j++){
                if(flag==true){
                    return true;
                }
                dfs(board,word,i,0,j);
            }
        }
       return flag;
    }
};

  兩端差別是dfs四個方向(上下左右),第二段程式碼需要上下左右全部進行遍歷,但是由於有時候在向上進行遍歷的時候就已經滿足條件,所以此時用或更好,因為在向上滿足條件時就不對剩下的進行dfs,減少了時間