Leetcode -- Spiral Matrix

来源:互联网 发布:阿里云企业邮箱桌面版 编辑:程序博客网 时间:2024/05/23 02:04

https://oj.leetcode.com/problems/spiral-matrix/

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 List<Integer> spiralOrder(int[][] matrix)


这一题和rotate image那题其实有点类似,都是对一个二维数组进行从外围到内的阅读操作。其实也可以用二重for循环来做。但是这里我采取的是另一种方法,为的是让答案显得更加直观。可以想象有上下左右四堵墙,按照下往上走一格(自左向右输出最下一行),右往左走一格(自下往上输出最右一列),上往下走一格(自右往左输出最上面一行),左往右走一格(自上往下输出最左一列)这样循环来进行,直到任意两堵墙相遇便表示输出结束了。这样会显得更加容易理解。下面是代码:


    public List<Integer> spiralOrder(int[][] matrix) {        List<Integer> res = new LinkedList<Integer>();        if(matrix.length == 0 || matrix[0].length == 0)            return res;        int left = 0, right = matrix[0].length - 1, bot = 0, top = matrix.length - 1;        while(true){            int curleft = left;            while(curleft <= right){                res.add(matrix[bot][curleft]);                curleft++;            }            bot++;            if(bot > top)                break;            int curbot = bot;            while(curbot <= top){                res.add(matrix[curbot][right]);                curbot++;            }            right--;            if(left > right)                break;            int curright = right;            while(curright >= left){                res.add(matrix[top][curright]);                curright--;            }            top--;            if(bot > top)                break;            int curtop = top;            while(curtop >= bot){                res.add(matrix[curtop][left]);                curtop--;            }            left++;            if(left > right)                break;        }        return res;    }


0 0
原创粉丝点击