Hướng dẫn thử thách
1 / 1
Implement the Depth-First Search Algorithm
In this lab, you will implement a graph traversal algorithm called <dfn>depth-first search</dfn>.
Whereas the <dfn>breadth-first search</dfn> searches incremental edge lengths away from the source node, <dfn>depth-first search</dfn> first goes down a path of edges as far as it can.
Once it reaches one end of a path, the search will backtrack to the last node with an un-visited edge path and continue searching.
Unlike breadth-first search, every time a node is visited, it doesn't visit all of its neighbors. Instead, it first visits one of its neighbors and continues down that path until there are no more nodes to be visited on that path.
To implement this algorithm, you'll want to use a stack (an array where the last element added is the first to be removed, following the <dfn>Last-In-First-Out</dfn> principle). A stack is helpful in depth-first search algorithms because, as you add neighbors to the stack, you want to visit the most recently added neighbors first and remove them from the stack.
A simple output of this algorithm is a list of nodes which are reachable from a given node. Therefore, you'll also want to keep track of the nodes you visit.
**Objective**: Fulfill the user stories below and get all the tests to pass to complete the lab.
**User Stories:**
1. You should have a function named `dfs`.
1. The `dfs` function should take two arguments:
- An undirected, adjacency matrix.
- A node label, which is the numeric value of the node between `0` and `n - 1`, where `n` is the total number of nodes in the graph.
1. The `dfs` function should implement the depth-first search algorithm to output a list of all nodes reachable from the node passed to it.
Vượt qua bài kiểm tra hiện tại để mở khóa bài tiếp theo.
main.py
UTF-8 • Tab Size: 2Kiểm tra bài:⌘↵