Top-left to Bottom-Right Diagonals Program In Python
Print all top-left to bottom-right diagonals from the top-right corner of a given RxC matrix
Understand the Problem
Problem Statement
The program must accept an integer matrix of size RxC as the input. The program must print the integers in the top-left to bottom-right diagonals from the top-right corner of the matrix.
Constraints
- 2 ≤ R, C ≤ 50
- 1 ≤ Matrix element value ≤ 1000
- Matrix elements are positive integers
- Input must be read from standard input
- Output must be written to standard output
Examples
3 3
9 4 5
9 5 3
7 7 55
4 3
9 5 5
9 7
7Starting from top-right corner, the diagonals are: [5], [4, 3], [9, 5, 5], [9, 7], [7]. Each diagonal follows the pattern where row - col is constant.
7 5
17 88 27 71 57
28 96 59 99 56
52 69 80 86 57
85 56 48 59 47
61 85 58 86 36
63 23 14 70 60
28 50 17 24 1357
71 56
27 99 57
88 59 86 47
17 96 80 59 36
28 69 48 86 60
52 56 58 70 13
85 85 14 24
61 23 17
63 50
28The algorithm extracts all top-left to bottom-right diagonals starting from the top-right element 57, moving down-left through each diagonal.
Solution
#include <stdio.h>
int main() {
int r, c;
scanf("%d %d", &r, &c);
int matrix[r][c];
// Read matrix
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
scanf("%d", &matrix[i][j]);
}
}
// Print diagonals from top-right to bottom-left
for (int diff = 1 - c; diff <= r - 1; diff++) {
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
if (i - j == diff) {
printf("%d ", matrix[i][j]);
}
}
}
printf("\n");
}
return 0;
}This C solution follows the same algorithm as the Python version. It reads the matrix dimensions and elements, then iterates through all possible diagonal constants. For each diagonal constant, it searches the entire matrix to find elements where the row index minus column index equals the diagonal constant, printing them in order.
Key points:
- Uses variable-length arrays (VLA) for matrix storage
- Three nested loops: outer for diagonal constants, inner two for matrix traversal
- Simple arithmetic check (i - j == diff) to identify diagonal elements