https://leetcode.com/problems.
my idea is to violently match the first letter, and then match the remaining letters up and down like a gluttonous snake, while using a vector k
plus a Hash
to convert the coordinates to a unique ID, to record the path. If you have already passed, the match does not pass.
after writing, I feel that this way of writing is wrong, and it should be quite different from the correct way of thinking. I don"t want to look at the answer directly, so I hope to get a hint of pointing out the shortcomings of the code and the right way of thinking.
-sharpdefine HashP(A, B) A <<16 | B
inline bool goTo(int& i, int& j, int& n, int& m, vector<int> k,
vector<vector<char>>& board, string& word){
k.push_back(HashP(i, j));
if(k.size() == word.size())
return true;
bool g1 = false, g2 = false, g3 = false, g4 = false;
int next = i - 1;
if(next >= 0 && board[next][j] == word[k.size()]
&& find(k.begin(), k.end(), HashP(next, j)) == k.end())
g1 = goTo(next, j, n, m, k, board, word);
next = i + 1;
if(next < n && board[next][j] == word[k.size()]
&& find(k.begin(), k.end(), HashP(next, j)) == k.end())
g2 = goTo(next, j, n, m, k, board, word);
next = j - 1;
if(next >= 0 && board[i][next] == word[k.size()]
&& find(k.begin(), k.end(), HashP(i, next)) == k.end())
g3 = goTo(i, next, n, m, k, board, word);
next = j + 1;
if(next < m && board[i][next] == word[k.size()]
&& find(k.begin(), k.end(), HashP(i, next)) == k.end())
g4 = goTo(i, next, n, m, k, board, word);
return g1 || g2 || g3 || g4;
}
bool exist(vector<vector<char>>& board, string word) {
int i,j;
int n = board.size(), m = board[0].size();
// if(word.size() > n * m) {
// return false;
// }
for(i = 0; i < n; iPP) {
for(j = 0; j < m; jPP) {
if(word.front() == board[i][j]) {
vector<int> k;
if(goTo(i, j, n, m, k, board, word)) {
return true;
}
}
}
}
return false;
}
Update:
The problem with timeout is that I wait for the result g1gramme
to all return
, and I should immediately return
when a result is true
. Thank you @ Caocong for your answer