算法系列——Spiral Matrix

来源:互联网 发布:淘宝流量和访客 编辑:程序博客网 时间:2024/06/05 09:29

题目描述

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

解题思路

题目要求我们顺时针打印数组。

注意两个部分,第一个控制打印继续的外层循环条件。
第二个 ,注意四个方向打印所需的条件。
详细的分析参考,http://zhedahht.blog.163.com/blog/static/254111742010111112236313/,讲的很好。

程序实现

class Solution {    public List<Integer> spiralOrder(int[][] matrix) {          List<Integer> res=new ArrayList<Integer>();      if(matrix==null||matrix.length==0)          return res;        int m=matrix.length;        int n=matrix[0].length;        int start=0;        while(start*2<m&&start*2<n){            int endX=n-1-start;//行坐标的终点            int endY=m-1-start;//列坐标终点            //从左到右打印一行            for(int i=start;i<=endX;i++)                res.add(matrix[start][i]);            //从上往下打印一列            if(start<endY){                for(int i=start+1;i<=endY;i++)                    res.add(matrix[i][endX]);            }            //从右往左打印一行            if(start<endX&&start<endY){                for(int i=endX-1;i>=start;i--)                    res.add(matrix[endY][i]);            }            //从下往上打印一列            if(start<endX&&start<endY-1){                 for(int i=endY-1;i>=start+1;i--)                    res.add(matrix[i][start]);            }              start++;        }         return res;    }}