难得力扣数据放水了hh
执行用时:4 ms, 在所有 C++ 提交中击败了88.84%的用户
内存消耗:8.2 MB, 在所有 C++ 提交中击败了90.43%的用户
class Solution {
public:
int n, m;
vector<string> res;
vector<vector<char>> g;
bool dfs(string &s, int x, int y, int u) {
if (u == s.size()) return true;
int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
g[x][y] = '.';
for (int i = 0; i < 4; i++) {
int a = x + dx[i], b = y + dy[i];
if (a >= 0 && a < n && b >= 0 && b < m && g[a][b] == s[u]) {
g[a][b] = '.';
if (dfs(s, a, b, u + 1)) {
g[a][b] = s[u];
g[x][y] = s[u - 1];
return true;
}
g[a][b] = s[u];
}
}
g[x][y] = s[u - 1];
return false;
}
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
n = board.size(), m = board[0].size();
g = board;
for (auto s : words) {
bool flag = true;
for (int i = 0; i < n && flag; i++) {
for (int j = 0; j < m; j++)
if (g[i][j] == s[0])
if (dfs(s, i, j, 1)) {
res.push_back(s);
flag = false;
break;
}
}
}
return res;
}
};
数据加强了,今天过不了了,回来补题。