您的位置:首页 > 其它

[leetcode]Word Search

2013-12-31 16:08 190 查看
枚举开始位置,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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: