输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵:
则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
模拟魔方逆时针旋转的方法,一直做取出第一行的操作
例如
1 2 3
4 5 6
7 8 9
输出并删除第一行后,再进行一次逆时针旋转,就变成:
6 9
5 8
4 7
继续重复上述操作即可。
def reversematrix(self,matrix):
s=matrix.shape
newmatrix=[]
for i in range(s[1]-1,-1,-1):
a=[]
for j in range(s[0]):
a.append(matrix[j,i])
newmatrix.append(a)
newmatrix=np.array(newmatrix)
return newmatrix
def printMatrix2(self, matrix):
newArray=[]
matrix=np.array(matrix)
print matrix
while len(matrix)!=0:
newArray.extend(matrix[0])
matrix=matrix[1:]
matrix=self.reversematrix(matrix)
return newArray
暴力使用循环遍历:
def printMatrix(self, matrix):
# write code here
size = len(matrix)
size = int(np.sqrt(size))
matrix = np.reshape(np.array(matrix), newshape=(size, size))
newArray = []
for index1 in range(0, int(size / 2)):
for index2 in range(index1, size - index1 - 1):
newArray.append(matrix[index1, index2])
for index3 in range(index1, size - index1 - 1):
newArray.append(matrix[index3, size - index1 - 1])
for index4 in range(size - index1 - 1, index1, -1):
newArray.append(matrix[size - index1 - 1, index4])
for index5 in range(size - index1 - 1, index1, -1):
newArray.append(matrix[index5, index1])
return newArray