Diagonal Traversal of a 2D Array - Problem Solution
Explore three methods to return the diagonal elements of a 2D array as a list.
Method 1
def solution(matrix): # Step 1: Create an empty list to store diagonal elements diagonal_elements = [] # Step 2: Iterate over each row of the 2D array for i in range(len(matrix)): # Steps 3 and 4: Find the diagonal elements and add to the list diagonal_elements.append(matrix[i][i]) # Step 5: Return the completed list return diagonal_elements
Using this function, you can traverse the input 2D array diagonally and return its elements.
Example Usage
Input/Output Example
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print(solution(matrix)) # Output: [1, 5, 9]
Lecture
AI Tutor
Publish
Design
Upload
Notes
Favorites
Help