题目:
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Example 1:
Input: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] Output: [1,2,3,6,9,8,7,4,5]Example 2:
Input: [ [1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12] ] Output: [1,2,3,4,8,12,11,10,9,5,6,7]就,螺旋打印一个矩阵。没啥技巧,主要就是通过设置四个不同的direction,再设定上下左右的边界,每加一次result就更新一次格子的index,如果走到边界了,就更新一下边界。主要就是处理边界比较烦,没什么技术上的难点。
Runtime: 0 ms, faster than 100.00% of Java online submissions for Spiral Matrix.
Memory Usage: 37.2 MB, less than 76.36% of Java online submissions for Spiral Matrix.
class Solution { public List<Integer> spiralOrder(int[][] matrix) { int rows = matrix.length; List<Integer> result = new ArrayList<>(); if (rows == 0) { return result; } int cols = matrix[0].length; int iRow = 0; int iCol = 0; int leftBound = 0; int rightBound = cols; int topBound = 0; int bottomBound = rows; int direction = 0; for (int i = 0; i < rows * cols; i++) { result.add(matrix[iRow][iCol]); if (direction == 0) { // left to right if (iCol < rightBound - 1) { iCol++; } else if (iCol == rightBound - 1) { direction = 1; iRow++; topBound++; } } else if (direction == 1) { // top to bottom if (iRow < bottomBound - 1) { iRow++; } else if (iRow == bottomBound - 1) { direction = 2; iCol--; rightBound--; } } else if (direction == 2) { // right to left if (iCol > leftBound) { iCol--; } else if (iCol == leftBound) { direction = 3; iRow--; bottomBound--; } } else if (direction == 3) { // bottom to top if (iRow > topBound) { iRow--; } else if (iRow == topBound) { direction = 0; iCol++; leftBound++; } } } return result; } }solutions里提到还有一种做法是按层来:
暂时不仔细研究了,就贴个代码吧
class Solution { public List < Integer > spiralOrder(int[][] matrix) { List ans = new ArrayList(); if (matrix.length == 0) return ans; int r1 = 0, r2 = matrix.length - 1; int c1 = 0, c2 = matrix[0].length - 1; while (r1 <= r2 && c1 <= c2) { for (int c = c1; c <= c2; c++) ans.add(matrix[r1][c]); for (int r = r1 + 1; r <= r2; r++) ans.add(matrix[r][c2]); if (r1 < r2 && c1 < c2) { for (int c = c2 - 1; c > c1; c--) ans.add(matrix[r2][c]); for (int r = r2; r > r1; r--) ans.add(matrix[r][c1]); } r1++; r2--; c1++; c2--; } return ans; } }: