Skip to content

Commit ecb9d9e

Browse files
committed
[feature]: unify format in notes
1 parent 523b80f commit ecb9d9e

File tree

2 files changed

+35
-35
lines changed

2 files changed

+35
-35
lines changed

notes/backtracking.md

Lines changed: 23 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ Main idea:
1111
1. **Base Case (Termination Condition)** is the condition under which the recursion stops. It prevents infinite recursion by providing an explicit solution for the simplest instance of the problem.
1212
2. **Recursive Case** is the part of the function where it calls itself with a modified parameter, moving towards the base case.
1313

14-
### Mathematical Foundation:
14+
### Mathematical Foundation
1515

1616
Recursion closely relates to mathematical induction, where a problem is solved by assuming that the solution to a smaller instance of the problem is known and building upon it.
1717

@@ -50,7 +50,7 @@ def factorial(n):
5050
return n * factorial(n - 1) # Recursive case
5151
```
5252

53-
#### Detailed Computation for $n = 5$:
53+
#### Detailed Computation for $n = 5$
5454

5555
Let's trace the recursive calls for `factorial(5)`:
5656

@@ -77,7 +77,7 @@ Now, we backtrack and compute the results:
7777

7878
Thus, $5! = 120$.
7979

80-
### Visualization with Recursion Tree:
80+
### Visualization with Recursion Tree
8181

8282
Each recursive call can be visualized as a node in a tree:
8383

@@ -113,7 +113,7 @@ Main idea:
113113
- **Implementation** of DFS can be achieved either through recursion, which implicitly uses the call stack, or by using an explicit stack data structure to manage the nodes.
114114
- **Applications** of DFS include tasks such as topological sorting, identifying connected components in a graph, solving puzzles like mazes, and finding paths in trees or graphs.
115115

116-
### Algorithm Steps:
116+
### Algorithm Steps
117117

118118
- **Start at the root node** by marking it as visited to prevent revisiting it during the traversal.
119119
- **Explore each branch** by recursively performing DFS on each unvisited neighbor, diving deeper into the graph or tree structure.
@@ -224,7 +224,7 @@ Objective:
224224
- Ensure that no two queens attack each other.
225225
- Find all possible arrangements that satisfy the above conditions.
226226

227-
#### Visual Representation:
227+
#### Visual Representation
228228

229229
To better understand the problem, let's visualize it using ASCII graphics.
230230

@@ -267,13 +267,13 @@ One of the possible solutions for placing 4 queens on a $4 \times 4$ chessboard
267267
- `Q` represents a queen.
268268
- Blank spaces represent empty cells.
269269

270-
#### Constraints:
270+
#### Constraints
271271

272272
- Only one queen per row.
273273
- Only one queen per column.
274274
- No two queens share the same diagonal.
275275

276-
#### Approach Using Backtracking:
276+
#### Approach Using Backtracking
277277

278278
Backtracking is an ideal algorithmic approach for solving the N-Queens problem due to its constraint satisfaction nature. The algorithm incrementally builds the solution and backtracks when a partial solution violates the constraints.
279279

@@ -289,7 +289,7 @@ High-Level Steps:
289289
8. When $N$ queens have been successfully placed without conflicts, record the solution.
290290
9. Continue the process to find all possible solutions.
291291

292-
#### Python Implementation:
292+
#### Python Implementation
293293

294294
Below is a Python implementation of the N-Queens problem using backtracking.
295295

@@ -322,7 +322,7 @@ def solve_n_queens(N):
322322
place_queen(0)
323323
return solutions
324324

325-
# Example usage:
325+
# Example usage
326326
N = 4
327327
solutions = solve_n_queens(N)
328328
print(f"Number of solutions for N={N}: {len(solutions)}")
@@ -343,7 +343,7 @@ for index, sol in enumerate(solutions):
343343
4. If no safe column is found, backtrack to the previous row.
344344
5. When a valid placement is found for all $N$ rows, record the solution.
345345

346-
#### All Solutions for $N = 4$:
346+
#### All Solutions for $N = 4$
347347

348348
There are two distinct solutions for $N = 4$:
349349

@@ -381,7 +381,7 @@ Board Representation: [2, 0, 3, 1]
381381
+---+---+---+---+
382382
```
383383

384-
#### Output of the Program:
384+
#### Output of the Program
385385

386386
```
387387
Number of solutions for N=4: 2
@@ -399,7 +399,7 @@ Q . . .
399399
. Q . .
400400
```
401401

402-
#### Visualization of the Backtracking Tree:
402+
#### Visualization of the Backtracking Tree
403403

404404
The algorithm explores the solution space as a tree, where each node represents a partial solution (queens placed up to a certain row). The branches represent the possible positions for the next queen.
405405

@@ -409,7 +409,7 @@ The algorithm explores the solution space as a tree, where each node represents
409409

410410
The backtracking occurs when a node has no valid branches (no safe positions in the next row), prompting the algorithm to return to the previous node and try other options.
411411

412-
#### Analysis:
412+
#### Analysis
413413

414414
I. The **time complexity** of the N-Queens problem is $O(N!)$ as the algorithm explores permutations of queen placements across rows.
415415

@@ -418,13 +418,13 @@ II. The **space complexity** is $O(N)$, where:
418418
- The `board` array stores the positions of the $N$ queens.
419419
- The recursion stack can go as deep as $N$ levels during the backtracking process.
420420

421-
#### Applications:
421+
#### Applications
422422

423423
- **Constraint satisfaction problems** often use the N-Queens problem as a classic example to study and develop solutions for placing constraints on variable assignments.
424424
- In **algorithm design**, the N-Queens problem helps illustrate the principles of backtracking and recursive problem-solving.
425425
- In **artificial intelligence**, it serves as a foundational example for search algorithms and optimization techniques.
426426

427-
#### Potential Improvements:
427+
#### Potential Improvements
428428

429429
- Implementing more efficient conflict detection methods.
430430
- Using heuristics to choose the order of columns to try first.
@@ -434,7 +434,7 @@ II. The **space complexity** is $O(N)$, where:
434434

435435
Given a maze represented as a 2D grid, find a path from the starting point to the goal using backtracking. The maze consists of open paths and walls, and movement is allowed in four directions: up, down, left, and right (no diagonal moves). The goal is to determine a sequence of moves that leads from the start to the goal without crossing any walls.
436436

437-
#### Maze Representation:
437+
#### Maze Representation
438438

439439
**Grid Cells:**
440440

@@ -494,7 +494,7 @@ Objective:
494494

495495
Find a sequence of moves from `S` to `G`, navigating only through open paths (`.`) and avoiding walls (`#`). The path should be returned as a list of grid coordinates representing the steps from the start to the goal.
496496

497-
#### Python Implementation:
497+
#### Python Implementation
498498

499499
```python
500500
def solve_maze(maze, start, goal):
@@ -549,7 +549,7 @@ else:
549549
print("No path found.")
550550
```
551551

552-
#### Recursive Function `explore(x, y)`:
552+
#### Recursive Function `explore(x, y)`
553553

554554
I. **Base Cases:**
555555

@@ -574,7 +574,7 @@ III. **Backtracking:**
574574
- Unmark the cell by setting `maze[x][y] = '.'`.
575575
- Return `False` to indicate that this path does not lead to the goal.
576576

577-
#### Execution Flow:
577+
#### Execution Flow
578578

579579
I. **Start at `(0, 0)`**:
580580

@@ -605,7 +605,7 @@ V. **Reaching the Goal**:
605605
- If a path is found, it prints "Path to goal:" followed by the list of coordinates in the path.
606606
- If no path exists, it prints "No path found."
607607

608-
#### Final Path Found:
608+
#### Final Path Found
609609

610610
The path from start to goal:
611611

@@ -615,7 +615,7 @@ The path from start to goal:
615615
(5, 5)]
616616
```
617617

618-
#### Visual Representation of the Path:
618+
#### Visual Representation of the Path
619619

620620
Let's overlay the path onto the maze for better visualization. We'll use `*` to indicate the path.
621621

@@ -643,13 +643,13 @@ Legend:
643643
. - Open path
644644
```
645645

646-
#### Advantages of Using Backtracking for Maze Solving:
646+
#### Advantages of Using Backtracking for Maze Solving
647647

648648
- Ensures that all possible paths are explored until the goal is found.
649649
- Only the current path and visited cells are stored, reducing memory usage compared to storing all possible paths.
650650
- Recursive implementation leads to clean and understandable code.
651651

652-
#### Potential Improvements:
652+
#### Potential Improvements
653653

654654
- This algorithm finds a path but not necessarily the shortest path.
655655
- To find the shortest path, algorithms like Breadth-First Search (BFS) are more suitable.

notes/graphs.md

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -225,7 +225,7 @@ To efficiently keep track of the traversal, BFS employs two primary data structu
225225
* A queue, typically named `unexplored` or `queue`, to store nodes that are pending exploration.
226226
* A hash table or a set called `visited` to ensure that we do not revisit nodes.
227227

228-
#### Algorithm Steps:
228+
#### Algorithm Steps
229229

230230
1. Begin from a starting vertex, $i$.
231231
2. Mark the vertex $i$ as visited.
@@ -324,13 +324,13 @@ Dijkstra's algorithm is a cornerstone in graph theory, designed to compute the s
324324
* **Input**: A weighted graph (where each edge has a value associated with it, representing the cost or distance) and a starting vertex `A`.
325325
* **Output**: An array `distances` where `distances[v]` represents the shortest path from `A` to vertex `v`.
326326

327-
#### Containers and Data Structures:
327+
#### Containers and Data Structures
328328

329329
* An array `distances`, initialized to `` for all vertices except the starting vertex which is initialized to `0`.
330330
* A hash table `finished` to keep track of vertices for which the shortest path has been determined.
331331
* A priority queue to efficiently select the vertex with the smallest tentative distance.
332332

333-
#### Algorithm Steps:
333+
#### Algorithm Steps
334334

335335
I. Initialize `distances[A] = 0` and `distances[v] = ∞` for all other vertices `v`.
336336

@@ -458,17 +458,17 @@ While the basic implementation of Dijkstra's algorithm runs in `O(n^2)` time, it
458458

459459
The Bellman-Ford algorithm is a graph search algorithm that finds the shortest path from a single source vertex to all vertices in a weighted graph. Unlike Dijkstra's algorithm, which works only for graphs with non-negative weights, Bellman-Ford is versatile enough to handle graphs in which some of the edge weights are negative.
460460

461-
#### Input & Output:
461+
#### Input & Output
462462

463463
* **Input**: A weighted graph (where each edge has an associated cost or distance) and a starting vertex `A`.
464464
* **Output**: An array `distances` where `distances[v]` represents the shortest path from `A` to vertex `v`.
465465

466-
#### Containers and Data Structures:
466+
#### Containers and Data Structures
467467

468468
* An array `distances`, initialized to `` for all vertices except the starting vertex which is initialized to `0`.
469469
* A predecessor array, often used to reconstruct the shortest path.
470470

471-
#### Algorithm Steps:
471+
#### Algorithm Steps
472472

473473
I. Initialize `distances[A] = 0` for the starting vertex and `distances[v] = ∞` for all other vertices.
474474

@@ -727,18 +727,18 @@ Such a subgraph is called a minimal spanning tree.
727727

728728
Prim's Algorithm is a greedy algorithm used to find a minimum spanning tree (MST) for a weighted undirected graph. The goal of the algorithm is to include every vertex in the graph into a tree while minimizing the total edge weights.
729729

730-
#### Input & Output:
730+
#### Input & Output
731731

732732
* **Input**: A connected, undirected graph with weighted edges.
733733
* **Output**: A minimum spanning tree, which is a subset of the edges that connects all the vertices together without any cycles and with the minimum possible total edge weight.
734734

735-
#### Containers and Data Structures:
735+
#### Containers and Data Structures
736736

737737
* An array `key[]` to store weights. Initially, `key[v] = ∞` for all `v` except the first vertex.
738738
* A boolean array `mstSet[]` to keep track of vertices included in MST. Initially, all values are `false`.
739739
* An array `parent[]` to store the MST.
740740

741-
#### Algorithm Steps:
741+
#### Algorithm Steps
742742

743743
I. Start with an arbitrary node as the initial MST node.
744744

@@ -835,17 +835,17 @@ The edges selected by Prim's algorithm in this case are: A-B, B-D, D-E, and A-C,
835835
### Kruskal's Algorithm
836836
Kruskal's Algorithm is another method to find the minimum spanning tree (MST) of a connected, undirected graph with weighted edges. It works by sorting all the edges from the lowest to highest weight, and then picking edges one by one, ensuring that the inclusion of each edge doesn't form a cycle.
837837

838-
#### Input & Output:
838+
#### Input & Output
839839

840840
* **Input**: A connected, undirected graph with weighted edges.
841841
* **Output**: A minimum spanning tree composed of a subset of the edges.
842842

843-
#### Containers and Data Structures:
843+
#### Containers and Data Structures
844844

845845
* A list or priority queue to sort all the edges based on their weights.
846846
* A disjoint-set (or union-find) structure to help in cycle detection and prevention.
847847

848-
#### Algorithm Steps:
848+
#### Algorithm Steps
849849

850850
I. Sort all the edges in increasing order based on their weights.
851851

0 commit comments

Comments
 (0)