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
.
这道题是在字母表中找单词,题目难度为Medium。
比较典型的回溯法题目,通过深度优先的方法查找字母表即可,对回溯法还不太清楚的同学可以先看下第51题(传送门)八皇后问题,这里就不再详细解释了。具体代码:
class Solution {
bool isExist(const vector<vector<char>>& board, vector<vector<bool>>& isUsed, const string& word, int idx, int r, int c) {
if(!isUsed[r][c] && board[r][c] == word[idx]) {
if(idx == word.size()-1) return true;
isUsed[r][c] = true;
if(r > 0) {
if(isExist(board, isUsed, word, idx+1, r-1, c)) return true;
}
if(r < board.size()-1) {
if(isExist(board, isUsed, word, idx+1, r+1, c)) return true;
}
if(c > 0) {
if(isExist(board, isUsed, word, idx+1, r, c-1)) return true;
}
if(c < board[0].size()-1) {
if(isExist(board, isUsed, word, idx+1, r, c+1)) return true;
}
isUsed[r][c] = false;
return false;
}
else return false;
}
public:
bool exist(vector<vector<char>>& board, string word) {
int row = board.size();
if(!row) return false;
int col = board[0].size();
if(!col) return false;
vector<vector<bool>> isUsed(row, vector<bool>(col, false));
for(int i=0; i<row; ++i) {
for(int j=0; j<col; ++j) {
if(isExist(board, isUsed, word, 0, i, j)) return true;
}
}
return false;
}
};