1. 程式人生 > >Word Search II

Word Search II

class Solution {
public:
    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
        if(words.empty()) return {};
        if(board.empty() || board[0].empty()) return {};
        vector<string> res;
        int n = board.size();
        int m = board[0].size();
        vector<vector<bool>> visited(n,vector<bool>(m,false));
        set<string> nwords(words.begin(), words.end());
        for(string a:nwords){
            if(a.empty()) continue;
            bool found = false;
            for(int i=0;i<n;i++){
                for(int j=0;j<m;j++){
                    if(helper(board, a, 0, i, j, visited)){
                        res.push_back(a);
                        found = true;
                        break;
                    }
                }
                if(found) break;
            }
        }
        return res;
    }
    bool helper(vector<vector<char>>& board, string& word, int pos, int i, int j, vector<vector<bool>>& visited){
        if(pos==word.size()) return true;
        if(i<0 || j<0 || i>=board.size() || j>=board[0].size()) return false;
        if(!visited[i][j] && board[i][j]==word[pos]){
            visited[i][j] = true;
            bool res = helper(board, word, pos+1, i-1, j, visited)
                || helper(board, word, pos+1, i, j-1, visited)
                || helper(board, word, pos+1, i+1, j, visited)
                || helper(board, word, pos+1, i, j+1, visited);
            visited[i][j] = false;
            return res;
        }
        return false;
    }
};