枚举开始位置,DFS验证
const int dx[] = {0,0,1,-1}; const int dy[] = {1,-1,0,0}; class Solution { public: unordered_set<long long> flag; bool check(vector<vector<char> > & board , string& word , int x , int y , int pos){ if(pos == word.size()) return true; for(int i = 0 ; i < 4 ; i++){ int tx = x + dx[i]; int ty = y + dy[i]; if(tx >= 0 && tx < board.size() && ty >= 0 && ty < board[tx].size()){ if(flag.find(tx*100000+ty) == flag.end() && board[tx][ty] == word[pos]){ flag.insert(tx*100000+ty); if(check(board , word , tx , ty , pos + 1)){ return true; }else{ flag.erase(tx*100000+ty); } } } } return false; } bool exist(vector<vector<char> > &board, string word) { if(word == "") return true; int size = board.size(); for(int i = 0 ; i < size ; i++){ for(int j = 0 ; j < board[i].size() ; j++){ if(board[i][j] == word[0]){ flag.clear(); flag.insert(i*100000 + j); if(check(board , word , i , j , 1)) return true; } } } return false; } };
by 1957