LeetCode 79.單詞搜索

一,問題描述

二,問題分析

整體思路

圖搜索策略DFS和回溯的思想

 標記數組

用一個二維數組visited數組標記元素是否被使用過

 循環遍歷

由於起點並不是唯一的,所以通過兩個循環遍歷整個數組找到開始的位置,即滿足wrod[0]的字母

 回溯的思想

找到滿足開始位置後,再開始搜索,搜索的方向爲上下左右四個方向,如果滿足接下來的條件,便繼續搜索,如果不滿足便回退一位開始搜索。

 注意事項

1.每次搜索到新的結點要判斷是否越界

2.對於已經搜索過的結點,且最後並不滿足要求,要及時將visited數組對應位置設爲未訪問,否則整個數組的每個位置就只能搜索一次

三,問題解答

class Solution {
private:
int d[4][2] = {{-1, 0}, {0,1}, {1, 0}, {0, -1}};
int m, n;           //矩陣邊界
 bool inArea( int x , int y ){
        return x >= 0 && x < m && y >= 0 && y < n;
    }
vector<vector<bool>> visited;
bool searchWord(vector<vector<char>>& board,string word,int index,int startx,int starty){
    //回溯的邊界條件
    if( index == word.size() - 1 )
            return board[startx][starty] == word[index];
    //遞歸函數主體
    if( board[startx][starty]==word[index] ){
        visited[startx][starty] = true;
        for(int i=0;i<4;i++){
            int newx = startx + d[i][0];
            int newy = starty + d[i][1];
            if( inArea(newx, newy) && !visited[newx][newy] &&
                    searchWord(board, word, index + 1, newx, newy))
                    return true;
        }
        visited[startx][starty] = false;
    }
    return false;
}
public:
    bool exist(vector<vector<char>>& board, string word) {
        m = board.size();
        n = board[0].size();
        visited = vector<vector<bool>> (m,vector<bool>(n,false));
        for(int i=0;i<board.size();i++){
            for(int j=0;j<board[i].size();j++){
                //遞歸函數調用
               if(searchWord(board,word,0,i,j)){
                   return true;
               }
            }
        }
        return false;
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章