中级农民
- 积分
- 217
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2017-11-30
- 最后登录
- 1970-1-1
|
212. Word Search II
白板复盘:
确认思路为backtracking,吸取上次教训,不用stack,用recursion
27分钟写完代码,上OJ跑的时候有一些runtime error,修正详见代码
take away: 使用pointer reference的时候要记得统一syntax,不要这里用pointer,那里又不用pointer
take away: 双层逻辑的backtracking中两层(起始层和递归层)都要写清楚branching和housekeeping
从白板上抄下来的代码如下:(红色字体为修改或添加的部分):
class Solution {
public:
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
/* 0. MISC */
/* 1. prep */
unordered_set<string> dict;
for(string word : words){
dict.emplace(word);
}
unordered_set<string> ansStore;
vector<vector<bool> > visited
(board.size(), vector<bool>(board[0].size(), false) );
string word = "";
unordered_set<string> prefixTable;
for(int i = 0; i < words.size(); ++i){
string prefix;
for(int j = 0; j < words[i].size(); ++j){
prefix += words[i][j];
prefixTable.emplace(prefix);
}
}
/* 2. key algorithm */
for(int i = 0; i < board.size(); ++i){
for(int j = 0; j < board[0].size(); ++j){
visited[i][j] = true; word += board[i][j];
WordSearchRec(board, dict, prefixTable, &ansStore, &visited, &word, i, j);
visited[i][j] = false; word.pop_back();
}
}
/* 3. answer */
vector<string> answer;
for(auto itr = ansStore.begin(); itr != ansStore.end(); ++itr){
answer.emplace_back(move(*itr));
}
return answer;
}
void WordSearchRec(const vector<vector<char> > & board,
unordered_set<string> &dict,
unordered_set<string> &prefixTable,
unordered_set<string> * ansStore,
vector<vector<bool> > * visited,
string * word, int i_, int j_){
if(dict.find(*word) != dict.end()){
ansStore->emplace(*word);
}
if(prefixTable.find(*word) == prefixTable.end()){
return;
}
vector<pair<int, int> > directions = {pair<int, int>(0, -1),
pair<int, int>(0, 1),
pair<int, int>(-1, 0),
pair<int, int>(1, 0)};
for(auto dir : directions){
int i = i_ + dir.first, j = j_ + dir.second;
if(!InRange(i, j, board))continue;
if((*visited)[i][j])continue;
(*visited)[i][j] = true; (*word) += board[i][j];
WordSearchRec(board, dict, prefixTable, ansStore, visited, word, i, j);
(*visited)[i][j] = false; word->pop_back();
}
}
bool InRange(int i, int j, const vector<vector<char> > &board){
return i >= 0 && i < board.size() && j >= 0 && j < board[i].size();
}
};
补充内容 (2018-10-30 23:41):
take away: 使用pointer reference的时候要记得统一syntax,不要这里用pointer,那里又不用pointer
take away: 双层逻辑的backtracking中两层(起始层和递归层)都要写清楚branching和housekeeping
补充内容 (2018-10-30 23:41):
倒数第二行InRange() function 最后一个assertion是 j < board[i].size()
补充内容 (2018-10-30 23:42):
好像显示不出来:board【i】.size() |
|