Dividing the matrices into submarines



  • N is the size of the matrix, K is the size of the submarine.
    The matrix is further introduced
    Accept N = 3, K = 2

    Our N*N matrix.

    1 2 1
    1 1 2
    1 1 1
    

    All size submarines K*K:

    [1 2
     1 1]
    

    [2 1
    1 2]

    [1 1
    1 1]

    [1 2
    1 1]

    How do you do the same job finding a submarine? What do you want me to do?
    The only thing you've done is create a three-dimensional set of k*k matrices filled with zeros.



  • If in the forehead,

    matrix = [[1, 2, 3, 'a'], [4, 5, 6, 'b'], [7, 8, 9, 'c'], [10, 11, 12, 'd']]
    size = (3, 2)
    

    for j in range(len(matrix) - size[1] + 1):
    for i in range(len(matrix[j]) - size[0] + 1):
    for y in range(size[1]):
    line = []
    for x in range(size[0]):
    line.append(matrix[j + y][i + x])
    print(line)
    print()

    In a blatant way, you have to go through the matrix so that one element of the submarine is within the range: matrix_width - submatrix_widthmatrix_height - submatrix_height

    And then using the coordinates of the first element, find all the other submarine elements in the matrix.

    or if it is written at the formula level, then:

    submatrix[x][y] = matrix[i + x][j + y]

    where (i, j) is the coordinates of the first (left top) submarine element in the matrix

    P. S.

    The code can be slightly simplified (for disgusts):

    [[[print([matrix[j + y][i + x] for x in range(size[0])]) for y in range(size[1])] + [print()] for i in range(len(matrix[j]) - size[0] + 1)] for j in range(len(matrix) - size[1] + 1)]



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2