原题:
word =
word =
解决方法:
代码:
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
.
解决方法:
依然是dfs的方法:
- 如果字符不匹配,我们直接返回。
- 如果匹配, 将该字符置空,然后往四周搜索下一个字符,直到所有字符都找出,表示字符串匹配了。
- 函数结束之前记住将原始字符重置回来。
代码:
bool dfs(vector<vector<char>>& board, int m, int n, int i, int j, const string& word, int index){
if (index >= word.size())
return true;
if (i < 0 || i >= m || j < 0 || j >= n || board[i][j] != word[index])
return false;
char temp = board[i][j];
board[i][j] = ' ';
bool found = false;
int dirs[4][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
for(auto dir: dirs){
int x = i + dir[0], y = j + dir[1];
if (dfs(board, m, n, x, y, word, index + 1)){
found = true;
break;
}
}
board[i][j] = temp;
return found;
}
bool exist(vector<vector<char>>& board, string word) {
if (board.empty() || board[0].empty())
return false;
if (word.empty())
return true;
int m = board.size(), n = board[0].size();
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if (dfs(board, m, n, i, j, word, 0))
return true;
}
}
return false;
}