AW Dev Rethought

⚖️ There are two ways of constructing a software design: one way is to make it so simple that there are obviously no deficiencies - C.A.R. Hoare

🧩 Python DSA Patterns — Matrix Patterns & 2D Traversals 🧭🐍


Description:

Matrix problems are a staple in interviews and real-world applications — from image grids to pathfinding in maps.

Understanding 2D traversal patterns helps you efficiently move, search, and explore within a grid.


📝 Row–Column Traversal

A matrix is essentially a 2D array.

Traversing it row by row or column by column is the foundation of all grid-based problems.

def traverse_matrix(matrix):
    print("Row-wise Traversal:")
    for i in range(len(matrix)):
        for j in range(len(matrix[0])):
            print(matrix[i][j], end=" ")
        print()

    print("\nColumn-wise Traversal:")
    for j in range(len(matrix[0])):
        for i in range(len(matrix)):
            print(matrix[i][j], end=" ")
        print()

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
traverse_matrix(matrix)

📝 Spiral Order Traversal

We move around the edges of the matrix in a clockwise spiral — top → right → bottom → left.

This is a key pattern for problems like Spiral Matrix and Boundary Traversal.

def spiral_order(matrix):
    result = []
    top, bottom = 0, len(matrix) - 1
    left, right = 0, len(matrix[0]) - 1

    while left <= right and top <= bottom:
        for j in range(left, right + 1):  # left → right
            result.append(matrix[top][j])
        top += 1

        for i in range(top, bottom + 1):  # top → bottom
            result.append(matrix[i][right])
        right -= 1

        if top <= bottom:
            for j in range(right, left - 1, -1):  # right → left
                result.append(matrix[bottom][j])
            bottom -= 1

        if left <= right:
            for i in range(bottom, top - 1, -1):  # bottom → top
                result.append(matrix[i][left])
            left += 1

    print("Spiral Order:", result)

spiral_order(matrix)
# Output: [1, 2, 3, 6, 9, 8, 7, 4, 5]

📝 Counting Islands (DFS on Matrix)

A common pattern — count connected regions of 1s (land) in a binary grid using DFS.

Each DFS explores all connected cells (up, down, left, right).

def count_islands(grid):
    if not grid:
        return 0

    rows, cols = len(grid), len(grid[0])
    visited = set()

    def dfs(r, c):
        if (
            r < 0 or c < 0 or
            r >= rows or c >= cols or
            grid[r][c] == '0' or (r, c) in visited
        ):
            return
        visited.add((r, c))
        dfs(r + 1, c)
        dfs(r - 1, c)
        dfs(r, c + 1)
        dfs(r, c - 1)

    count = 0
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] == '1' and (r, c) not in visited:
                dfs(r, c)
                count += 1

    print("Number of Islands:", count)

grid = [
    ["1","1","0","0"],
    ["1","0","0","1"],
    ["0","0","1","1"],
    ["0","0","0","0"]
]
count_islands(grid)
# Output: 2

✅ Takeaway

  • Matrix traversal builds intuition for graph and grid-based algorithms.
  • Learn standard directions:
    • 🔼 Up → (-1, 0)
    • 🔽 Down → (1, 0)
    • ◀️ Left → (0, -1)
    • ▶️ Right → (0, 1)
  • Common patterns: Spiral Order, Island Counting, Flood Fill, Word Search.

🏋️ Practice Problems

  1. Spiral Order Traversal
  2. Number of Islands
  3. Search a 2D Matrix
  4. Rotate Image (90°)
  5. Flood Fill

📂 Full Script

The blog covers the essentials — find the complete notebook with all snippets & extras on GitHub Repo 👉 Python DSA Patterns


Link copied!

Comments

Add Your Comment

Comment Added!