54. Spiral Matrix

来源:互联网 发布:更改mac地址 编辑:程序博客网 时间:2024/05/16 12:31

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

也就是如果在顶部的左边就往右,右往下,到底部后再往左。。。循环

marix [x][y++];

这里y是放在循环中自动加的

比如:


下面给出解:

public class Solution {    public List<Integer> spiralOrder(int[][] matrix) {        ArrayList<Integer> ans = new ArrayList<Integer>();        if(matrix==null || matrix.length==0) return ans;        int m = matrix.length;        int n = matrix[0].length;                int x=0,y=0;        while(m>0 && n>0){            //only one row/column situation            if(m==1){                for(int i=0;i<n;i++) ans.add(matrix[x][y++]);                break;            }else if(n==1){                for(int i=0;i<m;i++) ans.add(matrix[x++][y]);                break;            }                        //at the top--->right            for(int i=0;i<n-1;i++)                ans.add(matrix[x][y++]);            //at the right---->down            for(int i=0;i<m-1;i++)                ans.add(matrix[x++][y]);            //at the down----->left            for(int i=0;i<n-1;i++)                ans.add(matrix[x][y--]);            //at the left---->top            for(int i=0;i<m-1;i++)                ans.add(matrix[x--][y]);            x++;            y++;            m=m-2;            n=n-2;        }        return ans;    }}

m-2的原因是每次循环去头去尾的行和列

同时n-1或m-1是因为不减去的话超出bound

而x++和y++是因为使到达下一个行和列,因为循环过一次了嘛










原创粉丝点击