54. Spiral Matrix

来源:互联网 发布:傲剑金蛇数据 编辑:程序博客网 时间:2024/06/06 05:28

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 List<Integer> spiralOrder(int[][] matrix) {        List<Integer> res = new ArrayList<>();        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return res;        int cl = 0, cr = matrix[0].length-1;        int rl = 0, rr = matrix.length-1;        while (cl <= cr && rl <= rr) {            int i = rl, j = cl;            while (j <= cr) res.add(matrix[i][j++]);            j--;            i++;            while (i <= rr) res.add(matrix[i++][j]);            i--;            j--;            while (rl != rr && j > cl) res.add(matrix[i][j--]);            while (cl != cr && i > rl) res.add(matrix[i--][j]);            cl++;            cr--;            rl++;            rr--;        }        return res;    }}
public class Solution {    public List<Integer> spiralOrder(int[][] matrix) {        List<Integer> res = new ArrayList<Integer>();        if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return res;        int rowbegin = 0, rowend = matrix.length-1, colbegin = 0, colend = matrix[0].length-1;        while(rowbegin <= rowend && colbegin <= colend){            for(int i = colbegin; i <= colend; i++){                res.add(matrix[rowbegin][i]);            }            rowbegin++;            for(int i = rowbegin; i <= rowend; i++){                res.add(matrix[i][colend]);            }            colend--;            if(rowbegin <= rowend){                for(int i = colend; i >= colbegin; i--){                    res.add(matrix[rowend][i]);                }            }            rowend--;            if(colbegin <= colend){                for(int i = rowend; i >= rowbegin; i--){                    res.add(matrix[i][colbegin]);                   }            }            colbegin++;        }        return res;    }}
0 0
原创粉丝点击