顺时针打印矩阵
顺时针打印矩阵_牛客网
https://www.nowcoder.com/practice/9b4c81a02cd34f76be2659fa0d54342a?tpId=13&tqId=11172&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
思路1:顺时针打印就是按圈数循环打印,一圈包含两行或者两列,在打印的时候会出现某一圈中只包含一行,要判断从左向右打印和从右向左打印的时候是否会出现重复打印,同样只包含一列时,要判断从上向下打印和从下向上打印的时候是否会出现重复打印的情况,还要注意四个角有重复计数的情况。
def printMatrix(self, matrix): # write code here row = len(matrix) col = len(matrix[0]) l = [] start = 0 while row > 2*start and col > 2*start: endx = row - 1 - start endy = col - 1 - start for i in range(start, endy+1): l.append(matrix[start][i]) if start < endx: for i in range(start+1, endx+1):#角上的重复算了一次 l.append(matrix[i][endy]) if start < endx and start < endy: for i in range(endy-1, start-1, -1): l.append(matrix[endx][i]) if start < endx-1 and start < endy: for i in range(endx-1, start, -1): l.append(matrix[i][start]) start += 1 return l
思路2:定义四个变量,表示左上和右下的打印范围,一次旋转打印结束后,往对角分别前进和后退一个单位。
def printMatrix(self, matrix): # write code here rows=len(matrix) cols=len(matrix[0]) result=[] if rows==0 and cols==0: return result left,right,top,bottom = 0,cols-1,0,rows-1 while left<=right and top<=bottom: for i in range(left,right+1): result.append(matrix[top][i]) for i in range(top+1,bottom+1): result.append(matrix[i][right]) if top!=bottom: for i in range(right-1,left-1,-1): result.append(matrix[bottom][i]) if left!=right: for i in range(bottom-1,top,-1): result.append(matrix[i][left]) left+=1 right-=1 top+=1 bottom-=1 return result