题目
给定一个 m x n 的字符网格 board,以及一个单词 word,判断 board 当中是否包含 单词 word。
输入:board = [[“A”,“B”,“C”,“E”],[“S”,“F”,“C”,“S”],[“A”,“D”,“E”,“E”]], word = “ABCCED”
输出:true
原题链接:https://leetcode-cn.com/problems/word-search/
思路
DFS 回溯。找到就 return true,情况不对就 return false。每找到一个字母,就根据上下左右四个方向,继续找下一个字母。同时用一个 visited 数组来记录是否已经遍历过,以避免 “撞墙” 的情况。
- 复杂度分析
- 时间复杂度 O(mn*4^L)。设L为单词的长度,除了第一个字母外,其他的都有4个搜索方向。所以这个是个上界复杂度,实际上回溯过程中有不少剪枝,以及搜索到便返回true的情况,所以实际复杂度应该远小于这个上界。
- 空间复杂度 O(mn) 。开辟了个m x n 的 visited 数组。
代码
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
bool result = false;
int m = board.size();
int n = board[0].size();
vector<vector<bool>> visited(m, vector<bool>(n, false));
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (search(board, visited, word, m, n, i, j, 0)) {
return true;
}
}
}
return false;
}
bool search(vector<vector<char>>& board, vector<vector<bool>>& visited,
string& word, int& m, int& n, int i, int j, int index) {
if (index == word.size()) {
return true;
}
if (i < 0 || i >= m || j < 0 || j >= n || visited[i][j]) {
return false;
}
if (word[index] == board[i][j]) {
visited[i][j] = true;
if (search(board, visited, word, m, n, i - 1, j, index + 1) ||
search(board, visited, word, m, n, i + 1, j, index + 1) ||
search(board, visited, word, m, n, i, j - 1, index + 1) ||
search(board, visited, word, m, n, i, j + 1, index + 1)) {
return true;
}
visited[i][j] = false;
}
return false;
}
};