54. Spiral Matrix

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]

Title:

Snake output.

Ideas:

Unlike the previous serpentine filling, the matrix for this problem can be rectangular. But it can be analogous to the previous one, set top, left, right, down four parameters, simulate the snake shape for output, pay attention to the cut-off condition, when top==down||left==right can continue to add, such as 3* In the matrix of 3, when top=down, num[1][0], num[1][1] have not been added. So the cutoff condition is top==down+1||left==right+1.

Code:

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List list=new ArrayList();
        if(matrix.length==0)
            return list;
        int left=0,top=0,right=matrix[0].length-1,down=matrix.length-1;
        int t=0;
        while(left<=right||top<=down)
        {
            for(int i=left;i<=right;i++)
                list.add(matrix[top][i]);
            top++;
            if(top==down+1)
                break;
            for(int i=top;i<=down;i++)
                list.add(matrix[i][right]);
            right--;
            if(left==right+1)
                break;
            for(int i=right;i>=left;i--)
                list.add(matrix[down][i]);
            down--;
            if(top==down+1)
                break;
            for(int i=down;i>=top;i--)
                list.add(matrix[i][left]);
            left++;
            if(left==right+1)
                break;
        }
        return list;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325935007&siteId=291194637