Traversing Diagonals of a Grid
This is kind of a misleading title but I didn’t know what to call it. But what I wanted here to print each and every “diagonal” of this grid in both the left and right direction. For example, if left to right, then we’ll have
And we’ll print
Approach
We’re going to divide this problem into two subproblems. In the first subproblem, we’ll print the diagonals starting from the cells in the first column below.
In the second subproblem, we’ll print the remaining diagonals starting from the cells in the first row but skipping the first overlapping element with the first column since we did that in the first subproblem.
First Subproblem
We’ll iterate over the first column. From the first cell, we’ll print the following diagonal.
Next, we’ll move to the next cell in the column and print the diagonal starting from it.
And finally the last cell in the column.
This is process is captured in the following code:
The above code will output
Second Subproblem
We’ll iterate over the row column starting at the second cell and print the diagonal from there.
We’ll move on to the third cell and print the diagonal again.
Finally, we’ll print the very last diagonal.
This process is captured in the following code:
which will print the following
The Right to Left Direction
What about the complete other direction (right to left) below. How do we print these diagonals?
We’ll do the same thing, divide the problem into two subproblems and tackle each separately. This is captured in the following code: