diff --git a/README.md b/README.md index 8b9d292..4fdd25b 100644 --- a/README.md +++ b/README.md @@ -8,8 +8,10 @@ A repo for storing Python code and tracking learning progress. All programs are . ├── README.md ├── algorithms +│ ├── bfs.py │ ├── binary_search.py | ├── bubble_sort.py +| ├── dfs.py | ├── quicksort.py │ └── selection_sort.py ├── asynchronous_programming diff --git a/algorithms/bfs.py b/algorithms/bfs.py new file mode 100644 index 0000000..2f5d56f --- /dev/null +++ b/algorithms/bfs.py @@ -0,0 +1,48 @@ +from collections import deque + + +def bfs(graph: dict[str, list[str]], start: str, target: str) -> bool: + return _bfs(graph, start, target, seen=set()) + + +def _bfs( + graph: dict[str, list[str]], + node: str, + target: str, + seen: set[str], + ) -> bool: + + queue = deque([node]) + seen.add(node) + while queue: + current = queue.popleft() + if current == target: + return True + for child in graph[current]: + if child not in seen: + seen.add(child) + queue.append(child) + return False + + +def main() -> None: + graph = { + "(A)": ["(B)", "(C)"], + "(B)": ["(D)", "(E)"], + "(C)": ["(F)"], + "(D)": [], + "(E)": [], + "(F)": [], + } + start = "(A)" + target = "(F)" + + found = bfs(graph, start, target) + if found: + print(f"Target {target} was found!") + else: + print(f"Target {target} was not found.") + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/algorithms/dfs.py b/algorithms/dfs.py new file mode 100644 index 0000000..9555a7c --- /dev/null +++ b/algorithms/dfs.py @@ -0,0 +1,42 @@ +def dfs(graph: dict[str, list[str]], start: str, target: str) -> bool: + return _dfs(graph, start, target, seen=set()) + + +def _dfs( + graph: dict[str, list[str]], + node: str, + target: str, + seen: set[str] + ) -> bool: + + if node == target: + return True + seen.add(node) + for child in graph[node]: + if child not in seen: + if _dfs(graph, child, target, seen): + return True + return False + + +def main() -> None: + graph = { + "(A)": ["(B)", "(C)"], + "(B)": ["(D)", "(E)"], + "(C)": ["(F)"], + "(D)": [], + "(E)": [], + "(F)": [], + } + start = "(A)" + target = "(F)" + + found = dfs(graph, start, target) + if found: + print(f"Target {target} was found!") + else: + print(f"Target {target} was not found.") + + +if __name__ == "__main__": + main() \ No newline at end of file