Add notes
This commit is contained in:
parent
1829bf176e
commit
eef2af7756
1
notes/.gitignore
vendored
Normal file
1
notes/.gitignore
vendored
Normal file
@ -0,0 +1 @@
|
|||||||
|
book
|
6
notes/book.toml
Normal file
6
notes/book.toml
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
[book]
|
||||||
|
authors = ["Sainnhe Park"]
|
||||||
|
language = "en"
|
||||||
|
multilingual = false
|
||||||
|
src = "src"
|
||||||
|
title = "Notes"
|
4
notes/src/SUMMARY.md
Normal file
4
notes/src/SUMMARY.md
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Summary
|
||||||
|
|
||||||
|
- [深度优先遍历](./dfs.md)
|
||||||
|
- [广度优先遍历](./bfs.md)
|
36
notes/src/bfs.md
Normal file
36
notes/src/bfs.md
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
# 广度优先遍历
|
||||||
|
|
||||||
|
1. 保留全部节点状态,占用空间大
|
||||||
|
2. 无回溯操作(即无入栈、出栈操作),运行速度快
|
||||||
|
3. 对于解决最短或最少问题特别有效,而且寻找深度小(每个结点只访问一遍,结点总是以最短路径被访问,所以第二次路径确定不会比第一次短)
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
#include <queue>
|
||||||
|
|
||||||
|
// 新建一个数据结构,用来描述当前节点状态
|
||||||
|
typedef struct NodeStateStruct {
|
||||||
|
int para1;
|
||||||
|
int para2;
|
||||||
|
int para3;
|
||||||
|
} NodeState;
|
||||||
|
|
||||||
|
int main(void) {
|
||||||
|
// 讨论边界条件,比如字符串长度为 0 之类的
|
||||||
|
|
||||||
|
// 初始化一个队列
|
||||||
|
std::queue<NodeState> queue;
|
||||||
|
// 把根节点放进去
|
||||||
|
queue.push(NodeState {0, 0, 0});
|
||||||
|
// 开始迭代,当队列为空时结束迭代
|
||||||
|
NodeState node;
|
||||||
|
while (!queue.empty()) {
|
||||||
|
// 弹出队首
|
||||||
|
node = queue.front();
|
||||||
|
queue.pop();
|
||||||
|
// 遍历队首的所有子节点并把它们放到队尾
|
||||||
|
queue.push(/* child node 1 */);
|
||||||
|
queue.push(/* child node 2 */);
|
||||||
|
queue.push(/* child node 3 */);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
29
notes/src/dfs.md
Normal file
29
notes/src/dfs.md
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
# 深度优先遍历
|
||||||
|
|
||||||
|
1. 不保留全部节点状态,占用空间小
|
||||||
|
2. 有回溯操作(即有入栈、出栈操作,运行速度慢)
|
||||||
|
3. 深度很大的情况下效率不高
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
// 接收参数用来描述每个节点的状态
|
||||||
|
// 遍历结果可以用指针放在接收参数保存,也可以通过声明一个 class 的成员来保存
|
||||||
|
void dfs(int para1, int para2, int para3, std::vector<std::string> &result) {
|
||||||
|
// 讨论边界条件
|
||||||
|
// 只需要在这里讨论结束条件即可,初始化的工作会在 dfs 外完成
|
||||||
|
if (/* end condition */) {
|
||||||
|
/* statement */
|
||||||
|
}
|
||||||
|
// 当当前节点状态越界或不合法时,剪枝
|
||||||
|
if (/* invalid */) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// 当当前节点状态合法时,遍历当前节点的所有子节点
|
||||||
|
dfs(/* state of child node 1 */, result);
|
||||||
|
dfs(/* state of child node 2 */, result);
|
||||||
|
dfs(/* state of child node 3 */, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
void main(void) {
|
||||||
|
dfs(/* state of root node */, /* initial result */);
|
||||||
|
}
|
||||||
|
```
|
Loading…
Reference in New Issue
Block a user