Given a square matrix, find out count of numbers that are same in same row and same in both primary and secondary diagonals.
Input : 1 2 1 4 5 2 0 5 1 Output : 2 Primary diagonal is 1 5 1 Secondary diagonal is 1 5 0 Two elements (1 and 5) match in two diagonals and same. Input : 1 0 0 0 1 0 0 0 1 Output : 1 Primary diagonal is 1 1 1 Secondary diagonal is 0 1 0 Only one element is same.
We can achieve this in O(n) time, O(1) space and only one traversal. We can find current element in i-th row of primary diagonal as mat[i][i] and i-th element of secondary diagonal as mat[i][n-i-1].
This article is contributed by Himanshu Ranjan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Maximum size square sub-matrix with all 1s
- Print a given matrix in spiral form
- Search in a row wise and column wise sorted matrix
- A Boolean Matrix Question
- Matrix Chain Multiplication | DP-8
- Magic Square
- Print unique rows in a given boolean matrix
- Inplace (Fixed space) M x N size matrix transpose | Updated
- Maximum sum rectangle in a 2D matrix | DP-27
- Zigzag (or diagonal) traversal of Matrix
- Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
- Print all possible paths from top left to bottom right of a mXn matrix
- Count all possible paths from top left to bottom right of a mXn matrix
- Printing brackets in Matrix Chain Multiplication Problem
- Create a matrix with alternating rectangles of O and X