Spiral Matrix 螺旋数组

来源:互联网 发布:微信公众号域名备案 编辑:程序博客网 时间:2024/05/21 21:03

题目要求如下:

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

题目代码及解释:

import java.util.ArrayList;import java.util.List;/** * Created by dikongfeixing on 16/7/16. */public class SpiralMatrix54 {    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[][] dirs=new int[][]{{0,1},{1,0},{0,-1},{-1,0}};//定义方向,例如向左方向  即为j+1方向,即 i+0   j+1 {0,1}        int m=matrix.length;        int n=matrix[0].length;        int[] steps=new int[Math.min(m,n)*2+1];        /*计算  每次在每个方向上应该走的步数,   比如{{1,2,3}{4,5,6}}        假设从(0,-1)的位置开始走,一开始先向右走4步,再往下走1步,再往左走3步,再向上走0步        注意规律,隔项减一,直到减为了0,则代表走完了。        */        steps[0]=n;//按照上面的解释先初始化  步数  的数组        steps[1]=m-1;        for(int i=0;i<steps.length;i++)//根据规则  填充数组,直到最后一个元素为0        {            if(i%2==0&&i-2>=0){steps[i]=steps[i-2]-1;}            if(i%2==1&&i-2>=0){steps[i]=steps[i-2]-1;}        }        int idir=0;//idir代表目前转向的次数,因为每四次   转向回归一次,因此下面要与4求余        int it=0;//  it 记录当前  遍历  数组的   i  值        int ir=-1;//  ir  记录当前 遍历数组的  j  值,因为计算需要,        while(steps[idir]!=0)//当前方向应走的 步数  不为  0时循环        {            for(int i=0;i<steps[idir];i++)//走完指定的步数            {                it+= dirs[idir%4][0];//计算在当前的步数  对应的方向上   i与j应该如何增长,是  i++  i--  j++ j--                ir+= dirs[idir%4][1];                list.add(matrix[it][ir]);//将当前的  二维数组值  加入到List中。            }            idir++;//走完了当前方向上的步数,转向        }        return list;    }}

以上代码中,空间复杂度为O(n),其实可以将空间复杂度降低到O(1),方法是在   idir加的过程中  不断改变idir%2的值,是  steps[idir%2}=steps[idir%2]-1;

下面给出C++ 版本的实现 O(1)复杂度的代码:

vector<int> spiralOrder(vector<vector<int>>& matrix) {    vector<vector<int> > dirs{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};    vector<int> res;    int nr = matrix.size();     if (nr == 0) return res;    int nc = matrix[0].size();  if (nc == 0) return res;        vector<int> nSteps{nc, nr-1};        int iDir = 0;   // index of direction.    int ir = 0, ic = -1;    // initial position    while (nSteps[iDir%2]) {        for (int i = 0; i < nSteps[iDir%2]; ++i) {            ir += dirs[iDir][0]; ic += dirs[iDir][1];            res.push_back(matrix[ir][ic]);        }        nSteps[iDir%2]--;        iDir = (iDir + 1) % 4;    }    return res;}

以上两种代码  具有很好的复用性,当改变了  方向,改变了入口  位置时依然可以简单改变参数来得到结果。

0 0
原创粉丝点击