2

We have: a = [[1, 2, 4], [-1, 3, 4], [9, -3, 7]]

Diagonal traversal as a list: [1, -1, 2, 9, 3, 4]

n = int(input())
a = [[0]*n for _ in range(n)]
for i in range(n):
    a[i] = [int(j) for j in input().strip().split(" ")]

res = []
for j in range(n):
    for k in range(j + 1):
        res.append(a[j - k][k])
print(res)

How do I get the remaining two diagonals? I need to get: [-3, 4, 7]

SoH
  • 49
  • 7

2 Answers2

1

Try this. Define variables COL and ROW and then run the following function with your matrix.

def diagonalOrder(matrix) :       
    # There will be ROW+COL-1 lines in the output   
    for line in range(1, (ROW + COL)) :   
        # Get column index of the first element  
        # in this line of output. The index is 0   
        # for first ROW lines and line - ROW for   
        # remaining lines    
        start_col = max(0, line - ROW) 

        # Get count of elements in this line. 
        # The count of elements is equal to  
        # minimum of line number, COL-start_col and ROW     
        count = min(line, (COL - start_col), ROW) 

        # Print elements of this line     
        for j in range(0, count) :   
            print(matrix[min(ROW, line) - j - 1]   
                        [start_col + j], end = "\t")   
        print() 
1

First, see this 3x3 matrix with each element containing its row in the first digit and its column in the second digit.

00  01  02
10  11  12
20  21  22

The elements that you want are in the order:

00  10  01  20  11  02  21  12  22

Or in other perspective:

00
10 01
20 11 02
21 12
22

You can see that, in the first column of the numbers above, the first digits are 01222. This represents range(3) + [2, 2]. Now, look at the second digits of the first column. They are 00012 and represents [0, 0] + range(3).

Also, note that, in each row, each element decreases its first digit and increases its second digit until the element is equal to its inverse. You can see it more clearly in the third row. It starts at 20, goes to 11 and stop at 02, which is the inverse of 20, the initial number.

So, you can do something like:

def toNumber(i, j):
    return int(str(i) + str(j))

res = []
a = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]

list1 = list(range(3)) + [2]*2
list2 = [0]*2 + list(range(3))

for i, j in zip(list1, list2):
    inverse = int(str(toNumber(i, j))[::-1])
    while True:
        res.append(a[i][j])
        if toNumber(i, j) == inverse:
            break
        i -= 1
        j += 1

print(res)
enzo
  • 9,861
  • 3
  • 15
  • 38