简体   繁体   中英

Traverse matrix diagonally

I have got a board of NxM cells. I want to traverse it diagonally, from Up to Bottom. Another condition is that I just want to print diagonals that have at least 4 cells. I achieved it with a while and 3 conditionals but I am looking for a more simple way.

How is the board defined

board = []
    for t in range(BOARDWIDTH):
        board.append([EMPTY] * BOARDHEIGHT)

Imagine it contains the following...

  0  1  2  3  4  5  6
0 aa ab ac ad ae af ag
1 ah ai aj ak al am an
2 ao ap aq ar as at au
3 av aw ax ay az ba bb 
4 bc bd be bf bg bh bi 
5 bj bk bl bm bn bo bp 

How it should be traversed

ao aw be bm 
ah ap ax bf bn 
aa ai aq ay bg bo 
...
ad al at bb

First, convert your list to a numpy array:

array = np.array(board)

Then, simply use np.diagonal :

min_offset, max_offset = array.shape[0] - 4, array.shape[1] - 4
# To only select the sub-diagonals with more than 4 elements

for k in range(-min_offset, max_offset+1):
  print(array.diagonal(k))

Example:

array = np.arange(35).reshape(5,7)

# array = [[ 0  1  2  3  4  5  6]
#          [ 7  8  9 10 11 12 13]
#          [14 15 16 17 18 19 20]
#          [21 22 23 24 25 26 27]
#          [28 29 30 31 32 33 34]]

Outputs:

[ 7 15 23 31]
[ 0  8 16 24 32]
[ 1  9 17 25 33]
[ 2 10 18 26 34]
[ 3 11 19 27]

If you wish to print the transverse diagonals with the same criteria, simply flip the columns of your array and do as before:

array = array[:, ::-1]

with np.arange(35).reshape(5,7) , this outputs:

[13 19 25 31]
[ 6 12 18 24 30]
[ 5 11 17 23 29]
[ 4 10 16 22 28]
[ 3  9 15 21]

Use numpy.diag, eg for an index set I

for i in I:
    numpy.diag(M, i)

Also, if |i| <= max(M,N) - 4 then the diagonals have 4 entries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM