【矩阵】Spiral Matrix

来源:互联网 发布:什么样的人被借调 知乎 编辑:程序博客网 时间:2024/05/21 14:04

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

For example,
Given the following matrix:

[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ]]

You should return [1,2,3,6,9,8,7,4,5].

题意:螺旋打印矩阵

解法:把矩阵分成一圈一圈的单元,但需要考虑特殊情况,如只有一行或一列的情况

public class Solution {    public ArrayList<Integer> spiralOrder(int[][] matrix) {        ArrayList<Integer> l = new ArrayList<Integer>();        int row = matrix.length;        if(row == 0) return l;        int col = matrix[0].length;        if(col == 0) return l;                int up = 0, down = row-1, left = 0, right = col-1;        while(up <= down && left<=right){            for(int i=left; i<=right; i++) l.add(matrix[up][i]);            if(up == down) break;//若只有一行则已经全部打印完毕            for(int i=up+1; i<=down; i++) l.add(matrix[i][right]);            if(left == right) break;//若只有一列则全部打印完毕            for(int i=right-1; i>=left; i--) l.add(matrix[down][i]);            for(int i=down-1; i>up; i--) l.add(matrix[i][left]);            up++;            down--;            left++;            right--;        }        return l;    }}


0 0