给定一个二维数组 array,请返回「螺旋遍历」该数组的结果。
螺旋遍历:从左上角开始,按照 向右、向下、向左、向上 的顺序 依次 提取元素,然后再进入内部一层重复相同的步骤,直到提取完所有元素。
示例 1:
输入:array = [[1,2,3],[8,9,4],[7,6,5]] 输出:[1,2,3,4,5,6,7,8,9]
- class Solution {
- public int[] spiralArray(int[][] array) {
- if (array == null || array.length == 0 || array[0].length == 0) {
- return new int[0];
- }
- int rows = array.length, columns = array[0].length;
- int[] order = new int[rows * columns];
- int index = 0;
- int left = 0, right = columns - 1, top = 0, bottom = rows - 1;
- while (left <= right && top <= bottom) {
- for (int column = left; column <= right; column++) {
- order[index++] = array[top][column];
- }
- for (int row = top+1; row <= bottom; row++) {
- order[index++] = array[row][right];
- }
- if (left < right && top < bottom) {
- for (int column = right-1; column > left; column--) {
- order[index++] = array[bottom][column];
- }
- for (int row = bottom; row > top; row--) {
- order[index++] = array[row][left];
- }
- }
- left++;
- right--;
- top++;
- bottom--;
- }
- return order;
-
- }
- }
- class Solution {
- public List
spiralOrder(int[][] matrix) { - List
order = new ArrayList(); - if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
- return order;
-
- }
- int rows = matrix.length, cols = matrix[0].length;
- int left =0,right = cols - 1,top =0,bottom = rows -1;
- while(left <= right && top <= bottom){
- for(int col=left;col<=right;col++){
- order.add(matrix[top][col]);
- }
- for(int row = top+1;row<= bottom;row++){
- order.add(matrix[row][right]);
- }
- if(left < right && top < bottom){
- for(int col = right -1;col > left;col--){
- order.add(matrix[bottom][col]);
- }
- for(int row = bottom;row > top ;row--){
- order.add(matrix[row][left]);
- }
- }
- left++;
- right--;
- top++;
- bottom--;
-
- }
- return order;
- }
- }