Spiral Matrix

Spiral Matrix

问题:

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

思路:

  矩阵螺旋访问模板

我的代码:

public class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> list = new ArrayList<Integer>();
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0)   return list;
        int row = matrix.length;
        int col = matrix[0].length;
        int x1 = 0;
        int y1 = 0;
        while(row > 0 && col > 0)
        {
            int x2 = x1 + row - 1;
            int y2 = y1 + col - 1;
            for(int i = y1; i <= y2; i++)
            {
                list.add(matrix[x1][i]);
            }
            for(int i = x1 + 1; i < x2; i++)
            {
                list.add(matrix[i][y2]);
            }
            if(row > 1)
            {
                for(int i = y2; i >= y1; i--)
                {
                    list.add(matrix[x2][i]);
                }
            }
            if(col > 1)
            {
                for(int i = x2 - 1; i > x1; i--)
                {
                    list.add(matrix[i][y1]);
                }
            }
            row -= 2;
            col -= 2;
            x1 ++;
            y1 ++;
        }
        return list;
    }
}
View Code

学习之处:

  • 标记好左上角和右下角,防止越界
  • 用矩阵螺旋访问模板简单易行

posted on 2015-03-08 09:33  zhouzhou0615  阅读(157)  评论(0编辑  收藏  举报

导航