From eef2af7756f5b299842673ae5a9cd1e89d055509 Mon Sep 17 00:00:00 2001 From: Sainnhe Park Date: Mon, 14 Nov 2022 10:27:26 +0800 Subject: [PATCH] Add notes --- notes/.gitignore | 1 + notes/book.toml | 6 ++++++ notes/src/SUMMARY.md | 4 ++++ notes/src/bfs.md | 36 ++++++++++++++++++++++++++++++++++++ notes/src/dfs.md | 29 +++++++++++++++++++++++++++++ 5 files changed, 76 insertions(+) create mode 100644 notes/.gitignore create mode 100644 notes/book.toml create mode 100644 notes/src/SUMMARY.md create mode 100644 notes/src/bfs.md create mode 100644 notes/src/dfs.md diff --git a/notes/.gitignore b/notes/.gitignore new file mode 100644 index 0000000..7585238 --- /dev/null +++ b/notes/.gitignore @@ -0,0 +1 @@ +book diff --git a/notes/book.toml b/notes/book.toml new file mode 100644 index 0000000..eb972c6 --- /dev/null +++ b/notes/book.toml @@ -0,0 +1,6 @@ +[book] +authors = ["Sainnhe Park"] +language = "en" +multilingual = false +src = "src" +title = "Notes" diff --git a/notes/src/SUMMARY.md b/notes/src/SUMMARY.md new file mode 100644 index 0000000..b032d2d --- /dev/null +++ b/notes/src/SUMMARY.md @@ -0,0 +1,4 @@ +# Summary + +- [深度优先遍历](./dfs.md) +- [广度优先遍历](./bfs.md) diff --git a/notes/src/bfs.md b/notes/src/bfs.md new file mode 100644 index 0000000..f899589 --- /dev/null +++ b/notes/src/bfs.md @@ -0,0 +1,36 @@ +# 广度优先遍历 + +1. 保留全部节点状态,占用空间大 +2. 无回溯操作(即无入栈、出栈操作),运行速度快 +3. 对于解决最短或最少问题特别有效,而且寻找深度小(每个结点只访问一遍,结点总是以最短路径被访问,所以第二次路径确定不会比第一次短) + +```cpp +#include + +// 新建一个数据结构,用来描述当前节点状态 +typedef struct NodeStateStruct { + int para1; + int para2; + int para3; +} NodeState; + +int main(void) { + // 讨论边界条件,比如字符串长度为 0 之类的 + + // 初始化一个队列 + std::queue 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 */); + } +} +``` diff --git a/notes/src/dfs.md b/notes/src/dfs.md new file mode 100644 index 0000000..ee88965 --- /dev/null +++ b/notes/src/dfs.md @@ -0,0 +1,29 @@ +# 深度优先遍历 + +1. 不保留全部节点状态,占用空间小 +2. 有回溯操作(即有入栈、出栈操作,运行速度慢) +3. 深度很大的情况下效率不高 + +```cpp +// 接收参数用来描述每个节点的状态 +// 遍历结果可以用指针放在接收参数保存,也可以通过声明一个 class 的成员来保存 +void dfs(int para1, int para2, int para3, std::vector &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 */); +} +```