Matrix Diagonal Elements
EasyPractice library · +10 XPmatrixtraversal
Given a square matrix (2D grid) of integers, print all the elements that lie on its main diagonal (from top-left to bottom-right). The elements should be printed in the order they appear from top-left to bottom-right, separated by spaces.
Input
The first line contains an integer N, the dimension of the square matrix. The next N lines each contain N integers representing the matrix elements. The i-th line contains the elements of the i-th row.
Output
Print the N elements of the main diagonal, separated by spaces, on a single line.
Constraints
1 <= N <= 1000. Matrix elements are integers between -1000 and 1000.
Time limit 1 s (native code; slower languages get more)Memory 256 MB11 hidden tests
Example 1
Input
3 1 2 3 4 5 6 7 8 9
Output
1 5 9
The main diagonal elements are 1, 5, and 9.
Example 2
Input
2 10 20 30 40
Output
10 40
The main diagonal elements are 10 and 40.
Hints
# Read the input from stdin and print the answer.
import sys
def main():
data = sys.stdin.read().split()
# your code here
main()
Example 1 input
3 1 2 3 4 5 6 7 8 9
Example 2 input
2 10 20 30 40