🔗 leetcode.cn/problems/wo…
题目
- 给一个 m * n 的二维数组,每一格是一个英文大写字符
- 给一个字符串 word,如果 word 在网格中,则返回 true,否则 false
- 单词必须按照字母顺序,通过相邻的单元格内的字母构成
- 同一个单元格内的字母不允许被重复使用
思路
- 找到 word[0] 相同的二维数组下标,开始进行递归
- 递归依次判断四周的格子,是否匹配 word[index] 且没被使用,匹配上之后,继续递归
- 递归出口是,word 已经被找完
代码
class Solution {
public:
bool visit[10][10]
vector<vector<int>> dir
bool ans
void dfs(vector<vector<char>>& board, int x, int y, string& word, int index) {
if (ans) return
if (index >= word.size()) {
ans = true
return
}
int m = board.size()
int n = board[0].size()
for (int i = 0
int xx = x + dir[i][0]
int yy = y + dir[i][1]
if (xx < 0 || xx >= m || yy < 0 || yy >= n) continue
if (board[xx][yy] == word[index] && visit[xx][yy] == false) {
visit[xx][yy] = true
dfs(board, xx, yy, word, index + 1)
visit[xx][yy] = false
}
}
}
bool exist(vector<vector<char>>& board, string word) {
dir = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}
ans = false
for (int i = 0
for (int j = 0
if (board[i][j] == word[0]) {
memset(visit, 0, sizeof visit)
visit[i][j] = true
dfs(board, i, j, word, 1)
}
}
}
dfs(board, 0, 0, word, 0)
return ans
}
}