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.
Example:
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.
AC代码
bool dfs(int x, int y, int step, vector<vector<char>>& board, vector<vector<bool>>& book, string word) {
if (step == word.size()) return true;
if (x < 0 || x >= board.size() || y < 0 || y >= board[0].size() ||
book[x][y] == true || board[x][y] != word[step])
return false;
book[x][y] = true;
bool f = dfs(x - 1, y, step + 1, board, book, word) ||
dfs(x, y + 1, step + 1, board, book, word) ||
dfs(x, y - 1, step + 1, board, book, word) ||
dfs(x + 1, y, step + 1, board, book, word);
book[x][y] = false;
return f;
}
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
if (board.empty() || board[0].empty()) return false;
bool flag=false;
vector<vector<bool>> book(board.size());
for (auto& row : book) row.resize(board[0].size());
for (int i = 0; i < board.size(); ++i) {
for (int j = 0; j < board[0].size(); ++j) {
flag = dfs(i, j, 0, board, book, word);
if (flag) return flag;
}
}
return flag;
}
};
总结
时间复杂度和空间复杂度都很高,暂时没想到优化方法