Welcome to this enlightening lesson on Diagonal Traversal! In this comprehensive tutorial, we'll delve into a fascinating approach to traversing a matrix, offering you a unique perspective on data structures. Let's embark on this exciting journey!
Diagonal traversal is a technique used to traverse a matrix (2D array) following the diagonals. We have two types of diagonals:
Primary Diagonal: This diagonal runs from the top-left corner to the bottom-right corner by moving right for each row.
Secondary Diagonal: This diagonal runs from the top-right corner to the bottom-left corner by moving left for each row.
Diagonal traversal can be useful in various scenarios such as finding the minimum or maximum element, solving problems related to path finding, and more. It provides a different approach to accessing the elements in a matrix, making it a valuable tool in your programming arsenal.
Let's consider a 4x4 matrix:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
To traverse the primary diagonal, we start at the top-left corner (1) and move right for each row. The primary diagonal elements are: 1, 5, 9, and 13.
def primary_diagonal_traversal(matrix):
rows, cols = len(matrix), len(matrix[0])
# Start from top-left corner
x, y = 0, 0
while x < rows and y < cols:
print(matrix[x][y]) # Print the current element
x += 1 # Move down by one row
y += 1 # Move right by one column
# Example usage:
matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
primary_diagonal_traversal(matrix)For the secondary diagonal, we start at the top-right corner (8) and move left for each row. The secondary diagonal elements are: 8, 3, 10, and 16.
def secondary_diagonal_traversal(matrix):
rows, cols = len(matrix), len(matrix[0])
# Start from top-right corner
x, y = rows - 1, cols - 1
while x >= 0 and y >= 0:
print(matrix[x][y]) # Print the current element
x -= 1 # Move up by one row
y -= 1 # Move left by one column
# Example usage:
matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
secondary_diagonal_traversal(matrix)Given the following matrix:
Given the same matrix as the previous question:
That's all for today's lesson on Diagonal Traversal! We've learned about primary and secondary diagonals, why diagonal traversal is useful, and how to traverse them using Python.
Stay tuned for more engaging lessons on Data Structures and Algorithms here at CodeYourCraft! š”šā