双向移动二维矩阵的有效方法?

2024-04-29 05:22:27 发布

您现在位置:Python中文网/ 问答频道 /正文

给定一个二维矩阵,例如

l = [[1,1,1],
     [2,5,2],
     [3,3,3]])

在列和行上实现移位操作最有效的方法是什么?

例如

shift('up', l) 

[[2, 5, 2],
 [3, 3, 3],
 [1, 1, 1]]

但是

shift('left', l) 

[[1, 1, 1],
 [5, 2, 2],
 [3, 3, 3]]

由于this answer,我在两个深度上都使用collections.deque,但是当“向上”或“向下”只需要1个移位时,“左”或“右”需要N个移位(我的实现是对每行使用一个for循环)。

在C语言中,我认为这可以通过指针算法来改进(参见this answer)。

有更好的方法吗?

编辑:

  • 我的意思是,如果有一种方法可以避免N个移位。
  • 我们可以假设矩阵是平方的。
  • 轮班可以到位。

感谢马蒂诺指出了这个问题的这些要点。 对不起,我以前没有指出。


Tags: 方法answer算法编辑forshift矩阵this
3条回答

下面是一个非常有效的方法,它可以用于非平方矩阵:

DIRS = NONE, UP, DOWN, LEFT, RIGHT = 'unshifted', 'up', 'down', 'left', 'right'

def shift(matrix, direction, dist):
    """ Shift a 2D matrix in-place the given distance of rows or columns in the
        specified (NONE, UP, DOWN, LEFT, RIGHT) direction and return it.
    """
    if dist and direction in (UP, DOWN, LEFT, RIGHT):
        n = 0
        if direction in (UP, DOWN):
            n = (dist % len(matrix) if direction == UP else -(dist % len(matrix)))
        elif direction in (LEFT, RIGHT):
            n = (dist % len(matrix[0]) if direction == LEFT else -(dist % len(matrix[0])))
            matrix[:] = list(zip(*matrix))  # Transpose rows and columns for shifting.

        h = matrix[:n]
        del matrix[:n]
        matrix.extend(h)

        if direction in (LEFT, RIGHT):
            matrix[:] = map(list, zip(*matrix))  # Undo previous transposition.

    return matrix


if __name__ == '__main__':

    # Some non-square test matrices.
    matrix1 = [[1, 2, 3],
               [4, 5, 6],
               [7, 8, 9],
               [10, 11, 12]]

    matrix2 = [[1, 2, 3, 4],
               [5, 6, 7, 8],
               [9, 10, 11, 12]]

    def shift_and_print(matrix, direction, dist):
        GAP =  2  # Plus one for a ":" character.
        indent = max(map(len, DIRS)) + GAP
        print(direction
                + ': ' + (indent-2-len(direction))*' '
                + ('\n'+indent*' ').join(map(str, shift(matrix, direction, dist)))
                + '\n')

    for matrix in matrix1, matrix2:
        for direction in DIRS:
            shift_and_print(matrix, direction, 1)  # Printed results are cumulative.

输出(注意结果是累积的,因为操作已经执行到位,并且移位应用于上一次调用的结果):

no shift: [1, 2, 3]
          [4, 5, 6]
          [7, 8, 9]
          [10, 11, 12]

up:       [4, 5, 6]
          [7, 8, 9]
          [10, 11, 12]
          [1, 2, 3]

down:     [1, 2, 3]
          [4, 5, 6]
          [7, 8, 9]
          [10, 11, 12]

left:     [2, 3, 1]
          [5, 6, 4]
          [8, 9, 7]
          [11, 12, 10]

right:    [1, 2, 3]
          [4, 5, 6]
          [7, 8, 9]
          [10, 11, 12]

no shift: [1, 2, 3, 4]
          [5, 6, 7, 8]
          [9, 10, 11, 12]

up:       [5, 6, 7, 8]
          [9, 10, 11, 12]
          [1, 2, 3, 4]

down:     [1, 2, 3, 4]
          [5, 6, 7, 8]
          [9, 10, 11, 12]

left:     [2, 3, 4, 1]
          [6, 7, 8, 5]
          [10, 11, 12, 9]

right:    [1, 2, 3, 4]
          [5, 6, 7, 8]
          [9, 10, 11, 12]

可能是这样使用numpy

def shift(x, direction='up'):
    if direction == 'up':
        temp = range(x.shape[0])
        indicies = temp[1:] + [temp[0]]
        return x[indicies]
    elif direction == 'left':
        temp = range(x.shape[1])
        indicies = temp[1:] + [temp[0]]
        return x[:, indicies]
    else:
        print 'Error direction not known'

结果:

>>> shift(l, direction='up')
array([[2, 5, 2],
       [3, 3, 3],
       [1, 1, 1]])
>>> shift(l, direction='left')
array([[1, 1, 1],
       [5, 2, 2],
       [3, 3, 3]])
>>> shift(l, direction='to the moon')
Error direction not known

Numpy提供了一个名为roll()的方法来移动条目。

>>> import numpy as np
>>> x = np.arange(9)
>>> x = x.reshape(3, 3)
>>> print(x)

[[0 1 2]
 [3 4 5]
 [6 7 8]]

>>> x = np.roll(x, -1, axis=0) # up
>>> print(x)

[[3 4 5]
 [6 7 8]
 [0 1 2]]

>>> x = np.roll(x, 1, axis=0) # down
>>> print(x)

[[0 1 2]
 [3 4 5]
 [6 7 8]]

>>> x = np.roll(x, 2, axis=1) # right
>>> print(x)

[[1 2 0]
 [4 5 3]
 [7 8 6]]

>>> x = np.roll(x, -2, axis=1) # left
>>> print(x)    

[[0 1 2]
 [3 4 5]
 [6 7 8]]

我想与大多数解决方案相比,Numpy将非常有效
在矩阵运算方面,你不会被束缚在二维矩阵上。

相关问题 更多 >