LeetCode 79. 單詞搜索 (DFS搜索)

單詞搜索
時間複雜度:
O(n2len)O(n^2*len) (網格的每個點都要去遍歷一次,每次最多拓展4*len的點)

const int dx[] = {-1,0,1,0} ;
const int dy[] = {0,1,0,-1} ;
class Solution {
public:
    bool vis[210][210] = {0};
    int m,n;
    bool exist(vector<vector<char>>& board, string word) {
        m = board.size();
        n = board[0].size();
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                if(dfs(i,j,0,word,board)){
                    return true;
                }
            }
        }
        return false;
    }
    bool dfs(int x,int y,int idx,const string&s,vector<vector<char>>& board) {
        if(board[x][y] == s[idx]) {
            vis[x][y] = 1;
            if(idx==s.size()-1) {
                return true;
            }
            for(int k=0;k<4;k++) {
                int nx = x + dx[k];
                int ny = y + dy[k];
                if( nx>=0 && nx<m && ny>=0 && ny<n && !vis[nx][ny]) {
                    if(dfs(nx,ny,idx+1,s,board)){
                        return true;
                    }
                }
            }
            vis[x][y] = 0; //這一層全部搜索完,回溯。
        }
        return false;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章