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 =
[
[‘A’,’B’,’C’,’E’],
[‘S’,’F’,’C’,’S’],
[‘A’,’D’,’E’,’E’]
]
word = “ABCCED”, -> returns true,
word = “SEE”, -> returns true,
word = “ABCB”, -> returns false.
递归
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
size_t nr = board.size();
if (nr == 0) return false;
size_t nc = board[0].size();
size_t r = 0;
while (r != nr) {
for (size_t c = 0; c != board[r].size(); ++c) {
if (board[r][c] == word[0]) {
board[r][c] = '\0';
bool ret = findChar(board, r, c, string(word.begin() + 1, word.end()));
if (ret) return ret;
board[r][c] = word[0];
}
}
++r;
}
return false;
}
private:
bool findChar(vector<vector<char> >& board, size_t r, size_t c, string word) { // 以(r, c)为中心寻找word[0];
if (word.size() == 0) return true;
vector<pair<size_t, size_t> > rang;
if (c != board[0].size() - 1) rang.push_back(make_pair(r, c + 1));
if (c != 0) rang.push_back(make_pair(r, c - 1));
if (r != board.size() - 1) rang.push_back(make_pair(r + 1, c));
if (r != 0) rang.push_back(make_pair(r - 1, c));
for (auto p : rang) {
if (board[p.first][p.second] == word[0]) {
board[p.first][p.second] = '\0';
bool ret = findChar(board, p.first, p.second, string(word.begin() + 1, word.end()));
if (ret) return ret;
board[p.first][p.second] = word[0];
}
}
return false;
}
};
参考后
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
size_t nr = board.size();
if (nr == 0) return false;
size_t nc = board[0].size();
size_t r = 0;
while (r != nr) {
for (size_t c = 0; c != board[r].size(); ++c) {
bool ret = findChar(board, r, c, word);
if (ret) return ret;
}
++r;
}
return false;
}
private:
bool findChar(vector<vector<char> >& board, int r, int c, string word) { // 以(r, c)为中心寻找word[0];
if (word.size() == 0) return true;
if (r < 0 || r >= board.size() || c < 0 || c >= board[0].size()) return false;
if (board[r][c] == word[0]) {
board[r][c] = '\0';
bool ret = (findChar(board, r, c - 1, string(word.begin() + 1, word.end()))
|| findChar(board, r, c + 1, string(word.begin() + 1, word.end()))
|| findChar(board, r - 1, c, string(word.begin() + 1, word.end()))
|| findChar(board, r + 1, c, string(word.begin() + 1, word.end())));
if (ret) return ret;
board[r][c] = word[0];
}
return false;
}
};