lqdoj
  • NEW!
    NEW!  Connect Ideas Across Notes
    Save time and share insights. With Paragraph Citation, you can quote others’ work with source info built in. If someone cites your note, you’ll see a card showing where it’s used—bringing notes closer together.
    Got it
        • Sharing URL Link copied
        • /edit
        • View mode
          • Edit mode
          • View mode
          • Book mode
          • Slide mode
          Edit mode View mode Book mode Slide mode
        • Customize slides
        • Note Permission
        • Read
          • Owners
          • Signed-in users
          • Everyone
          Owners Signed-in users Everyone
        • Write
          • Owners
          • Signed-in users
          • Everyone
          Owners Signed-in users Everyone
        • Engagement control Commenting, Suggest edit, Emoji Reply
      • Invite by email
        Invitee

        This note has no invitees

      • Publish Note

        Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

        Your note will be visible on your profile and discoverable by anyone.
        Your note is now live.
        This note is visible on your profile and discoverable online.
        Everyone on the web can find and read all notes of this public team.

        Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

        Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

        Explore these features while you wait
        Complete general settings
        Bookmark and like published notes
        Write a few more notes
        Complete general settings
        Write a few more notes
        See published notes
        Unpublish note
        Please check the box to agree to the Community Guidelines.
        View profile
      • Commenting
        Permission
        Disabled Forbidden Owners Signed-in users Everyone
      • Enable
      • Permission
        • Forbidden
        • Owners
        • Signed-in users
        • Everyone
      • Suggest edit
        Permission
        Disabled Forbidden Owners Signed-in users Everyone
      • Enable
      • Permission
        • Forbidden
        • Owners
        • Signed-in users
      • Emoji Reply
      • Enable
      • Versions and GitHub Sync
      • Note settings
      • Note Insights New
      • Engagement control
      • Make a copy
      • Transfer ownership
      • Delete this note
      • Insert from template
      • Import from
        • Dropbox
        • Google Drive
        • Gist
        • Clipboard
      • Export to
        • Dropbox
        • Google Drive
        • Gist
      • Download
        • Markdown
        • HTML
        • Raw HTML
    Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Help
    Menu
    Options
    Engagement control Make a copy Transfer ownership Delete this note
    Import from
    Dropbox Google Drive Gist Clipboard
    Export to
    Dropbox Google Drive Gist
    Download
    Markdown HTML Raw HTML
    Back
    Sharing URL Link copied
    /edit
    View mode
    • Edit mode
    • View mode
    • Book mode
    • Slide mode
    Edit mode View mode Book mode Slide mode
    Customize slides
    Note Permission
    Read
    Owners
    • Owners
    • Signed-in users
    • Everyone
    Owners Signed-in users Everyone
    Write
    Owners
    • Owners
    • Signed-in users
    • Everyone
    Owners Signed-in users Everyone
    Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # DFS - BFS ## Note Để đệ quy được sâu, thêm 2 dòng này vào đầu bài: ```python import sys sys.setrecursionlimit(độ sâu đệ quy cần dùng) ``` DFS: Depth-first search (Tìm kiếm theo chiều sâu) BFS: Breadth-first search (Tìm kiếm theo chiều rộng) ## Mục tiêu chung của DFS + BFS Hai thuật toán duyệt này nhìn được dùng để duyệt qua toàn bộ tất cả các đỉnh (trong một thành phần liên thông), để từ đó lấy thông tin của các đỉnh. ## DFS Bắt đầu từ một đỉnh $u$, ta lần lượt duyệt các đỉnh bằng cách sau: 1. Đánh dấu đỉnh $u$ hiện tại đã thăm 2. Chọn một đỉnh $v$ kề $u$ sao cho $v$ chưa được thăm. - Nếu tìm được đỉnh $v$ phù hợp, chuyển sang thăm đỉnh $v$ và làm tương tự hai điều 1 & 2 - Ngược lại, quay về đỉnh $u$ cũ ngay trước đó để thực hiện lại bước 2. ![](https://i.imgur.com/XHb7YkI.png) Nếu ta đã dựng được danh sách kề `graph`, ta có thể code như sau: ```python= visited = [False] * (n + 1) # đánh dấu tất cả chưa được thăm def dfs(u): visited[u] = True # (thông thường) xử lý đỉnh u for v in graph[u]: # với mỗi đỉnh kề với u if visited[v] == True: # đỉnh nào thăm rồi thì bỏ qua continue dfs(v) ``` ```cpp= vector<int> graph[MAX]; bool visited[MAX] = {}; void dfs(int u){ visited[u] = true; // (thông thường) xử lý đỉnh u ở đây for (int v: graph[u]){ if (visited[v] == true) continue; dfs(v); } } ``` **Nhắc lại:** DFS/BFS chỉ duyệt được các đỉnh cùng thuộc thành phần liên thông (đối với đồ thị vô hướng **Tính chất:** Nếu sắp xếp lại danh sách cạnh, sẽ luôn cho được đường đi có **thứ tự từ điển nhỏ nhất**. - Chứng minh: giả sử $u$ kề $v_1$ và $v_2$, và $v_1 < v_2$. Để có thứ tự từ điển nhỏ nhất, $u$ **bắt buộc** phải đi tới $v_1$ trước, thay vì $v_2$. Vì vậy thuật toán trên phải tạo được đường đi tttđ nhỏ nhất. ## BFS **Kiến thức cần học:** QUEUE Chiến thuật duyệt của BFS: 1. Tạo ra một danh sách chờ các đỉnh 2. Từ một đỉnh, ta duyệt hết toàn bộ các đỉnh chưa được thăm kề nó, rồi cho vào danh chờ 3. Tiếp tục rút một đỉnh từ danh sách chờ và làm lại điều 2 ![](https://i.imgur.com/RGAi1KV.png) ![](https://i.imgur.com/2zJMF3o.png) Nếu thứ tự duyệt như trên, ta có tính chất: khoảng cách của các đỉnh được duyệt tăng dần. ```cpp= bool visited[MAX]; int distance[MAX]; queue<int> q; void bfs(int root){ visited[root] = true; distance[root] = 0; q.push(root); while (!q.empty()){ int node = q.front(); q.pop(); for (int child: graph[node]) if (visited[child] == true) continue; else { // giống dòng đầu visited[child] = true; distance[child] = distance[node] + 1; q.push(child); } } } ``` ## Bài tập ### BDFS (DFS Cơ bản) Duyệt các đỉnh từ $1 \rightarrow n$, đỉnh nào chưa được thăm tức là có tplt chưa được thăm, đỉnh nào thăm rồi thì bỏ qua. ![](https://i.imgur.com/reqrZ4B.png) ### BFS (BFS Cơ bản) Bước đầu tiên, ta sẽ BFS bắt đầu từ đỉnh S ```cpp= bool visited[MAX]; int distance[MAX]; queue<int> q; void bfs(int root){ visited[root] = true; distance[root] = 0; q.push(root); while (!q.empty()){ int node = q.front(); q.pop(); for (int child: graph[node]) if (visited[child] == true) continue; else { // giống dòng đầu visited[child] = true; distance[child] = distance[node] + 1; q.push(child); } } } ``` Sau đó, theo đề bài, ta sắp xếp tăng dần theo khoảng cách, nếu bằng nhau thì theo chỉ số $\Rightarrow$ lưu lại bằng mảng `pair` ```cpp= pair<int, int> results[MAX]; for (int i = 1; i <= n; i++) results[i] = {distance[i], i}; sort(results + 1, results + 1 + n); for (int i = 1; i <= n; i++) cout << results[i].second << ' ' << results[i].first << '\n'; ``` ### CSES 1666 - building road Cho một đồ thị vô hướng $n$ đỉnh $m$ cạnh, cần tạo thêm bao nhiêu cạnh để đảm bảo cả $n$ đỉnh liên thông? #### Solution Giả sử đồ thị bị chia thành $X$ vùng liên thông, ta cần dùng $X-1$ cạnh để nối chúng lại thành một thể. Để xác định một thành phần liên thông, ta dùng thuật toán duyệt trên đồ thị (DFS): - duyệt i = 1 -> n, nếu đỉnh nào chưa được thăm => chưa thuộc tplt nào cả => dfs(i) để duyệt tplt mới Để dựng một cách nối, ta chỉ cần bốc ra $X$ đỉnh đại diện của $X$ thành phần liên thông, rồi nối vào nhau thành một đường thẳng. ```python= # setrecursionlimit: 10^5 # nhập vào visited = [False] * (n + 1) def dfs(u): visited[u] = True for v in graph[u]: if visited[v] == True: continue dfs(v) số_tplt = 0 đại_diện = [] for i = 1-> n if visited[i] == False: # có một tplt mới số_tplt += 1; đại_diện.append(i) dfs(i) print(số_tplt - 1) for i = 1 -> số_tplt - 1: print(đại_diện[i - 1], đại_diện[i]) ``` ### Đường đi đẹp nhất dựa vào tính chất của đường đi DFS, ta sắp xếp lại danh sách cạnh rồi duyệt. để có đỉnh của đường đi, ta lưu lại. khi vừa tới $t$, dừng luôn. ![](https://i.imgur.com/VgfrlFz.png) ### Đếm phòng ![](https://hackmd.io/_uploads/Bk-XUYPb6.png) khai báo kiểu dữ liệu tọa độ ô, tạo sẵn 4 hướng: ![](https://i.imgur.com/SiPA20D.png) duyệt các ô: ![](https://i.imgur.com/VWPu7wD.png) thuật toán: ![](https://i.imgur.com/3mtIf7s.png) ## cses1667 Đề yêu cầu tìm đường đi ngắn nhất từ $1$ tới $n$, và in ra đường đi đó. Ta sẽ BFS từ đỉnh $1$, và ngoài lưu `distance[i]`, thì với mỗi đỉnh $i$ ta lưu thêm `prev[i]`, cho biết trên đường đi ngắn nhất từ $1 \rightarrow i$, đỉnh ngay phía trước nó là đỉnh nào. ```cpp= int prev[MAX]; void bfs(int root){ visited[root] = true; distance[root] = 0; q.push(root); while (!q.empty()){ int node = q.front(); q.pop(); for (int child: graph[node]) if (visited[child] == true) continue; else { // giống dòng đầu visited[child] = true; distance[child] = distance[node] + 1; prev[child] = node; // THÊM DÒNG NÀY VÀO q.push(child); } } } ``` Để in ra đường đi từ 1 tới n, ta lần lượt đi ngược từ $n \rightarrow prev[n] \rightarrow prev[prev[n]] \rightarrow \dots \rightarrow 1$ ```cpp= vector<int> answer; void trace(){ int node = n; answer.push_back(node); while (node != 1){ node = prev[node]; answer.push_back(node); } // đảo ngược thứ tự reverse(answer.begin(), answer.end()); } ```

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Google Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully