原题链接:单词搜索
个人解法
思路:
dfs直接搜素,注意可以剪枝,若dfs当前位置字符不对应相等则可以直接退出,直到满足字符相等且长度已经枚举到和word一样长时返回true。
时间复杂度: O ( m n ∗ l e n ( w o r d ) ) O(mn * len(word)) O(mn∗len(word))
代码:
class Solution {
public:
vector<int> dx = {-1, 0, 1, 0};
vector<int> dy = {0, 1, 0, -1};
vector<vector<bool>> st;
bool dfs(vector<vector<char>> &board, string &word, int x, int y, int u) {
if(board[x][y] != word[u]) return false;
if(u == word.size() - 1) return true;
st[x][y] = true;
int m = board.size(), n = board[0].size();
for(int i = 0;i < 4;i ++) {
int tx = x + dx[i], ty = y + dy[i];
if(tx < 0 || tx >= m || ty < 0 || ty >= n || st[tx][ty]) continue;
if(dfs(board, word, tx, ty, u + 1)) return true;
}
st[x][y] = false;
return false;
}
bool exist(vector<vector<char>>& board, string word) {
int m = board.size(), n = board[0].size();
st = vector<vector<bool>> (m + 1, vector<bool>(n + 1));
for(int x = 0; x < m; x ++) {
for(int y = 0;y < n; y ++) {
if(dfs(board, word, x, y, 0)) return true;
}
}
return false;
}
};