单词搜索-

const int N = 20;

int dx[] = {0, 0, 1, -1};

int dy[] = {1, -1, 0, 0};

class Solution {

public:

bool dfs(int i, int j, int n, int m, vector<vector<char>>& board,

string& word, vector<vector<bool>>& st, int cnt) {

if (board[i][j] != word[cnt])

return false;

if (cnt == word.size()-1)

return true;

st[i][j]=true;

for (int k = 0; k < 4; ++k) {

int x = dx[k] + i, y = dy[k] + j;

if (x < 0 || x >= n || y < 0 || y >= m || st[x][y])

continue;

if (

dfs(x, y, n, m, board, word, st, cnt+1))

return true;

}

st[i][j]=false;

return false;

}

bool exist(vector<vector<char>>& board, string word) {

int n = board.size(), m = board[0].size();

string path;

for (int i = 0; i < n; ++i) {

for (int j = 0; j < m; ++j) {

vector<vector<bool>> st(n, vector<bool>(m, false));

if (board[i][j] == word[0] &&dfs(i, j, n, m, board, word, st, 0))

return true;

}

}

return false;

}

};

相关推荐
zx_zx_1232 小时前
定长滑动窗口和不定长滑动窗口
数据结构·算法
mjhcsp2 小时前
C++ 梯度下降法(Gradient Descent):数值优化的核心迭代算法
开发语言·c++·算法
yunyun321232 小时前
跨语言调用C++接口
开发语言·c++·算法
m0_518019482 小时前
C++中的装饰器模式变体
开发语言·c++·算法
xushichao19892 小时前
高性能密码学库
开发语言·c++·算法
m0_518019482 小时前
C++代码混淆与保护
开发语言·c++·算法
m0_569881472 小时前
C++中的智能指针详解
开发语言·c++·算法
blackicexs2 小时前
第九周第三天
算法
自信150413057592 小时前
选择排序算法
c语言·数据结构·算法·排序算法