题目
给定一个二维网格和一个单词,找出该单词是否存在于网格中。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例:
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
给定 word = "ABCCED", 返回 true
给定 word = "SEE", 返回 true
给定 word = "ABCB", 返回 false
提示:
board 和 word 中只包含大写和小写英文字母。
1 <= board.length <= 200
1 <= board[i].length <= 200
1 <= word.length <= 10^3
思路
采用深度优先搜索,用一个二维数组纪录访问过的元素,如果成功匹配单词则返回,如果匹配失败回溯,在某一个位置的的探索还需要一个一维数组记录访问过的元素的位置。
C++解法
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
vector<vector<bool>> visited(board.size(), vector<bool>(board[0].size(), false));
vector<pair<int, int>> backtract_items;
bool issucced = false;
for (int i = 0; i < board.size(); ++i) {
for (int j = 0; j < board[0].size(); ++j) {
if (board[i][j] != word[0]) continue;
dfs(board, visited, i, j, word, 0, issucced, backtract_items);
if (issucced) return true;
for (auto item: backtract_items) visited[item.first][item.second] = false;
backtract_items.clear();
}
}
return false;
}
void dfs(vector<vector<char>>& board, vector<vector<bool>> & visited, int row, int col, string & word, int index, bool & succeed, vector<pair<int,int>> & latest_visited) {
if (index == word.size()) { succeed = true; return; }
if (row < 0 || row >= board.size() || col < 0 || col >= board[0].size() || visited[row][col] || word[index] != board[row][col]) return;
visited[row][col] = true;
latest_visited.push_back({row, col});
int directions[4][2] = {{row + 1, col}, {row - 1, col}, {row, col - 1}, {row, col + 1}};
vector<pair<int, int>> backtract_items;
for (int i = 0; i < 4 && !succeed; ++i) {
dfs(board, visited, directions[i][0], directions[i][1], word, index + 1, succeed, backtract_items);
if (i != 0) {
for (auto item: backtract_items) visited[item.first][item.second] = false;
backtract_items.clear();
}
}
}
};
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/word-search
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
网友评论