首页 > 代码库 > 54. Spiral Matrix

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

思路:

 [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ]

step 1: add top line- from left to right
step 2: add right line - from top to bottom
step 3: add bottom line - from right to left
step 4 : add left line - from bottom to top

注意边界条件: [2 3] 1.用总个数来限制,calling method会增加复杂度2.用 top bottom left right关系来限制
Solution 1:
public class Solution {    public List<Integer> spiralOrder(int[][] matrix) {        List<Integer> res=new ArrayList<Integer>();        if(matrix==null||matrix.length==0)        {            return res;        }        int l=matrix[0].length;        int h=matrix.length;        int total=l*h;        int left=0,top=0,right=l-1,bottom=h-1;        while(res.size()<total)        {        for(int i=left;i<=right;i++)        {            res.add(matrix[top][i]);        }        top++;        if(res.size()<total)        {        for(int j=top;j<=bottom;j++)        {            res.add(matrix[j][right]);        }        right--;        }        if(res.size()<total)        {        for(int k=right;k>=left;k--)        {            res.add(matrix[bottom][k]);        }        bottom--;        }        if(res.size()<total)        {        for(int m=bottom;m>=top;m--)        {            res.add(matrix[m][left]);        }        left++;        }        }        return res;    }}

Solution2:

public class Solution {    public List<Integer> spiralOrder(int[][] matrix) {        List<Integer> res=new ArrayList<Integer>();        if(matrix==null||matrix.length==0)        {            return res;        }        int l=matrix[0].length;        int h=matrix.length;        int total=l*h;        int left=0,top=0,right=l-1,bottom=h-1;        while(res.size()<total)        {        for(int i=left;i<=right;i++)        {            res.add(matrix[top][i]);        }        top++;        if(top>bottom)        {            break;        }        for(int j=top;j<=bottom;j++)        {            res.add(matrix[j][right]);        }        right--;                if(right<left)        {            break;        }        for(int k=right;k>=left;k--)        {            res.add(matrix[bottom][k]);        }        bottom--;            if(bottom<top)        {            break;        }        for(int m=bottom;m>=top;m--)        {            res.add(matrix[m][left]);        }        left++;                }        return res;    }}

 

54. Spiral Matrix