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
- Spiral Matrix 螺旋数组
- Spiral Matrix 螺旋打印数组 递归
- Spiral Matrix 螺旋矩阵
- Spiral Matrix 螺旋矩阵I
- LeetCode Spiral Matrix(螺旋矩阵)
- [LintCode] 螺旋矩阵 Spiral Matrix
- 54. Spiral Matrix 螺旋矩阵
- *[Lintcode]Spiral Matrix螺旋矩阵
- [LeetCode] Spiral Matrix 螺旋输出矩阵
- Spiral Matrix II 螺旋矩阵II
- [LeetCode]-Spiral Matrix I&II 螺旋矩阵
- LeetCode Spiral Matrix II (生成螺旋矩阵)
- [LintCode] 螺旋矩阵II Spiral Matrix II
- LeetCode 54. Spiral Matrix(螺旋矩阵)
- PAT 1105. Spiral Matrix (螺旋输出)
- leetcode 59. Spiral Matrix II (螺旋矩阵)
- 54/59 Spiral Matrix 螺旋矩阵
- Spiral Matrix II:螺旋打印方阵
- 物质之学(二)
- 一个程序员的Ubuntu安装的那些软件
- 编程实现打印出26个字母的所有子集
- 文章标题
- poj1185 炮兵阵地(状压dp)
- Spiral Matrix 螺旋数组
- 最大比率问题
- 最小生成树算法简单分析
- java容器学习总结(一)
- MT MD MTd MDd在引入第三方库时的选择
- scala的几个小程序
- Python清空指定文件夹下所有文件的方法
- 放暑假了!!!!!!!!!!
- 2016年7月16日学习 scratch 声控抽奖