decription:
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
For example,
Given board =
[
["ABCE"],
["SFCS"],
["ADEE"]
]
word = "ABCCED"
, -> returns true
,word = "SEE"
, -> returns true
,word = "ABCB"
, -> returns false
.
slove:
class Solution {
public:
bool exist(vector<vector<char> > &board, string word) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
bool got_it = false;
vector<char> tp;
int h = board.size();
int w = board.at(0).size();
bool* visit = new bool[h * w];
for(int k = 0; k < w * h; ++ k) visit[k] = false;
for(int i = 0; i < h; ++ i) {
tp = board.at(i);
for(int j = 0; j < tp.size(); ++ j) {
if(tp.at(j) == word[0]) {
got_it = run(visit, board, i, j, word, 0);
if(got_it) {
return got_it;
} else {
for(int k = 0; k < w * h; ++ k) visit[k] = false;
}
}
}
}
return got_it;
}
bool run(bool visit[], const vector<vector<char> >& board, int i, int j, string word, int idx) {
if(i >= board.size() || i < 0) {
return false;
}
if(j >= board.at(i).size() || j < 0) {
return false;
}
if(idx >= word.length()) {
return false;
}
if(visit[i * board.at(0).size() + j] == true) {
return false;
}
if(board.at(i).at(j) == word.at(idx)) {
visit[i * board.at(0).size() + j] = true;
if(idx == word.length() - 1) {
return true;
}
return run(visit, board, i + 1, j, word, idx + 1) ||
run(visit, board, i - 1, j, word, idx + 1) ||
run(visit, board, i, j - 1, word, idx + 1) ||
run(visit, board, i, j + 1, word, idx + 1);
}
return false;
}
};
坑:
递归时保存访问信息的数组更新有问题