AW Dev Rethought

βœ‚οΈ Perfection is achieved not when there is nothing more to add, but when there is nothing left to take away - Antoine de Saint-ExupΓ©ry

🧩 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!