美文网首页ACM题库~
LeetCode 54. Spiral Matrix

LeetCode 54. Spiral Matrix

作者: 关玮琳linSir | 来源:发表于2017-09-19 13:50 被阅读13次

    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].

    题意:转圈往里扫,边扫边放到集合里面。

    java代码:

     public List<Integer> spiralOrder(int[][] matrix) {
            List<Integer> res = new ArrayList<Integer>();
    
            if ( matrix == null || matrix.length == 0) {
                return res;
            }
    
            int rowBegin = 0;
            int rowEnd = matrix.length - 1;
            int colBegin = 0;
            int colEnd = matrix[0].length - 1;
    
            while( rowBegin <= rowEnd && colBegin <= colEnd) {
                //traverse right
                for(int i=colBegin;i<=colEnd;i++)
                    res.add(matrix[rowBegin][i]);
                rowBegin++;
    
                //traverse down
                for(int i=rowBegin;i<=rowEnd;i++)
                    res.add(matrix[i][colEnd]);
                colEnd--;
    
                //traverse left
                if(rowBegin <= rowEnd) {
                    for(int i=colEnd;i>=colBegin;i--)
                        res.add(matrix[rowEnd][i]);
                    rowEnd--;
                }
    
                //traverse up
                if(colBegin <= colEnd) {
                    for(int i=rowEnd;i>=rowBegin;i--)
                        res.add(matrix[i][colBegin]);
                    colBegin++;
                }
            }
    
            return res;
        }
    

    相关文章

      网友评论

        本文标题:LeetCode 54. Spiral Matrix

        本文链接:https://www.haomeiwen.com/subject/kvmwsxtx.html