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
.
无他,递归而已。应该有非递归的,不过本人水平不够,只能直接递归了。
class Solution {
public:
bool isExisting(vector<vector<char> > &board, vector<vector<char> > &record, string word, int ii, int jj) {
if(word == "") return true;
int row = board.size();
int col = board[0].size();
if(ii > 0 && board[ii - 1][jj] == word[0] && record[ii - 1][jj] == 0) {
record[ii - 1][jj] = 1;
if(isExisting(board, record, word.substr(1, word.length() - 1), ii - 1, jj))
return true;
record[ii - 1][jj] = 0;
}
if(ii < row - 1 && board[ii + 1][jj] == word[0] && record[ii + 1][jj] == 0) {
record[ii + 1][jj] = 1;
if(isExisting(board, record, word.substr(1, word.length() - 1), ii + 1, jj))
return true;
record[ii + 1][jj] = 0;
}
if(jj > 0 && board[ii][jj - 1] == word[0] && record[ii][jj - 1] == 0) {
record[ii][jj - 1] = 1;
if(isExisting(board, record, word.substr(1, word.length() - 1), ii, jj - 1))
return true;
record[ii ][jj - 1] = 0;
}
if(jj < col - 1 && board[ii][jj + 1] == word[0] && record[ii][jj + 1] == 0) {
record[ii][jj + 1] = 1;
if(isExisting(board, record, word.substr(1, word.length() - 1), ii, jj + 1))
return true;
record[ii][jj + 1] = 0;
}
return false;
}
bool exist(vector<vector<char> > &board, string word) {
if(word == "") return true;
int row = board.size();
if(row == 0) return false;
int col = board[0].size();
if(col == 0) return false;
vector<vector<char> > records(row, vector<char>(col, 0));
for(int ii = 0; ii < row; ii ++) {
for(int jj = 0; jj < col; jj ++) {
if(board[ii][jj] == word[0]) {
records[ii][jj] = 1;
if(isExisting(board, records, word.substr(1,word.length() - 1), ii, jj))
return true;
records[ii][jj] = 0;
}
}
}
return false;
}
};