原题链接
题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
示例 1
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
示例 2
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]
限制
0 <&#61; matrix.length <&#61; 100
0 <&#61; matrix[i].length <&#61; 100
解法&#xff1a;边框控制
这道题目太经典&#xff0c;期末实训、蓝桥杯、都遇见了&#xff0c;控制好边界范围就行
public int[] spiralOrder(int[][] matrix) {if(matrix &#61;&#61; null || matrix.length &#61;&#61; 0 || matrix[0].length &#61;&#61; 0) return new int[0];int[] result &#61; new int[matrix.length * matrix[0].length];int left &#61; 0, right &#61; matrix[0].length - 1, top &#61; 0, bottom &#61; matrix.length - 1, index &#61; -1;while (left <&#61; right && top <&#61; bottom){for (int i &#61; left; i <&#61; right; i&#43;&#43;) {result[&#43;&#43;index] &#61; matrix[top][i];}for (int i &#61; top &#43; 1; i <&#61; bottom; i&#43;&#43;) {result[&#43;&#43;index] &#61; matrix[i][right];}if(left < right && top < bottom){for (int i &#61; right - 1; i >&#61; left ; --i) {result[&#43;&#43;index] &#61; matrix[bottom][i];}for (int i &#61; bottom - 1; i > top; --i) {result[&#43;&#43;index] &#61; matrix[i][left];}}&#43;&#43;left;--right;&#43;&#43;top;--bottom;}return result;
}
提交结果