一週刷完劍指offer-19-順時針列印矩陣
阿新 • • 發佈:2020-09-17
順時針列印矩陣
1. 題目描述
輸入一個矩陣,按照從外向裡以順時針的順序依次打印出每一個數字
2. 示例
[[ 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.
3. 解題思路
順時針走,即向右->向下->向左->向上,一共要走(長*寬)步。
遇到邊界就改變方向,當向上碰到頂的時候,四個邊界都縮小。思路簡單,一個迴圈即可!
4. Java實現
import java.util.ArrayList; public class Solution { public ArrayList<Integer> printMatrix(int [][] matrix) { ArrayList<Integer> res = new ArrayList(); int rows = matrix.length; // 行的大小 int cols = matrix[0].length; // 列的大小 if (rows == 0 || cols == 0){ return res; } // 從左到右開始遍歷,right最右邊【列】,從上到下,bottom最底部【行】 int left = 0, right = cols-1, top = 0, bottom = rows -1; while(left <= right && top <= bottom){ // 從左到右開始遍歷 for(int i = left; i <= right; i++){ res.add(matrix[top][i]); } // 從上到下開始遍歷 for (int i = top+1; i <= bottom; i++){ res.add(matrix[i][right]); } // 從下往上開始遍歷 if (top != bottom){ for (int i = right-1; i>= left; i--){ res.add(matrix[bottom][i]); } } //從 右往左開始遍歷 if (left != right){ for (int i = bottom-1; i > top; i--){ res.add(matrix[i][left]); } } left++; right--; top++; bottom--; } return res; } }
5. Python實現
# -*- coding:utf-8 -*- class Solution: # matrix型別為二維列表,需要返回列表 def printMatrix(self, matrix): if matrix == None: return rows = len(matrix) columns = len(matrix[0]) start = 0 while rows > start * 2 and columns > start * 2: self.PrintMatrixInCircle(matrix, columns, rows, start) start += 1 print('') def PrintMatrixInCircle(self, matrix, columns, rows, start): endX = columns - 1 - start endY = rows - 1 - start # 從左到右列印一行 for i in range(start, endX+1): number = matrix[start][i] print(number, ' ', end='') # 從上到下列印一行 if start < endY: for i in range(start+1, endY+1): number = matrix[i][endX] print(number, ' ', end='') # 從右到左列印一行 if start < endX and start < endY: for i in range(endX-1, start-1, -1): number = matrix[endY][i] print(number, ' ', end='') # 從下到上列印一行 if start < endX and start < endY-1: for i in range(endY-1, start, -1): number = matrix[i][start] print(number, ' ', end='')
如果您覺得本文有用,請點個“在看”