Skip to content

Commit f4061a7

Browse files
committed
Add ju-zhen-lu-jing
1 parent f830f12 commit f4061a7

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

advanced_algorithm/backtrack.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,38 @@ void backtrack(vector<int>& nums, vector<int> track, vector<bool>& visited, vect
241241
}
242242
```
243243
244+
### [ju-zhen-zhong-de-lu-jing-lcof](https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof/)
245+
246+
> 请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。
247+
248+
```cpp
249+
bool exist(vector<vector<char>>& board, string word) {
250+
for(int i = 0; i < board.size(); i++){
251+
for(int j = 0; j < board[0].size(); j++){
252+
if(bfs(board, i, j, word, 0)) return true;
253+
}
254+
}
255+
256+
return false;
257+
}
258+
259+
bool bfs(vector<vector<char>>& board, int i, int j, string word, int idx){
260+
if(idx >= word.length() || i < 0 || i >= board.size() || j < 0 || j >= board[0].size() ||
261+
board[i][j] != word[idx])
262+
return false;
263+
board[i][j] = '0';
264+
if(idx == word.length() - 1) return true;
265+
bool flag = bfs(board, i-1, j, word, idx+1) ||
266+
bfs(board, i+1, j, word, idx+1) ||
267+
bfs(board, i, j-1, word, idx+1) ||
268+
bfs(board, i, j+1, word, idx+1);
269+
board[i][j] = word[idx]; //别忘了回溯
270+
return flag;
271+
}
272+
```
273+
274+
275+
244276
## 练习
245277

246278
- [ ] [subsets](https://leetcode-cn.com/problems/subsets/)

0 commit comments

Comments
 (0)