为什么80%的码农都做不了架构师?>>>   

问题:

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

解决:

① 没有特别简化的方法,只能一步步的来。如果矩阵只有一行或者一列,那么无需转圈,依次输出即可。其他情况均需转圈:从左到右,从上到下,从右到左,从下到上。 从大圈依次循环到小圈即可。

class Solution { //3ms
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new ArrayList<>();
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return res;
        getSpiral(matrix,0,0,matrix.length,matrix[0].length,res);
        return res;
    }
    public void getSpiral(int[][] matrix,int x,int y,int rows,int cols,List<Integer> res){
        if(rows <= 0 || cols <= 0) return;
        for (int i = 0;i < cols ;i ++ ) {//由左到右
            res.add(matrix[x][y + i]);
        }
        for (int i = 1;i < rows - 1 ;i ++ ) {//由上到下
            res.add(matrix[x + i][y + cols - 1]);
        }
        if(rows > 1){//由右到左
            for (int i = cols - 1;i >= 0 ;i -- ) {
                res.add(matrix[x + rows - 1][y + i]);
            }
        }
        if(cols > 1){
            for (int i = rows - 2;i > 0 ;i -- ) {//由下到上
                res.add(matrix[x + i][y]);
            }
        }
        getSpiral(matrix,x + 1,y + 1,rows - 2,cols - 2,res);
    }
}

② 使用top,bottom,right,left记录四个角。可以减少错误。只需要判断四个边界是否相撞即可。

class Solution{ //3ms
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new ArrayList<Integer>();
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return res;
        }
        int rows = matrix.length;
        int cols = matrix[0].length;
        int left = 0;
        int right = cols - 1;
        int top = 0;
        int bottom = rows - 1;
        while (left <= right && top <= bottom) {
            for (int i = left; i <= right; i ++) {
                res.add(matrix[top][i]);
            }
            for (int i = top + 1; i <= bottom - 1; i ++) {
                res.add(matrix[i][right]);
            }
            if (top != bottom) {
                for (int i = right; i >= left; i --) {
                    res.add(matrix[bottom][i]);
                }    
            }
            if (left != right) {
                for (int i = bottom - 1; i >= top + 1; i --) {
                    res.add(matrix[i][left]);
                }    
            }
            left ++;
            right --;
            top ++;
            bottom --;
        }
        return res;
    }
}

③ 在discuss中看到以下方法:用Iterator来实现,记录2个方向数组,分别表示在x方向,y方向的前进方向。1表示右或是下,-1表示左或是向上,0表示不动作。

// 1: means we are visiting the row by the right direction.
// -1: means we are visiting the row by the left direction.
int[] x = {1, 0, -1, 0};    
// 1: means we are visiting the colum by the down direction.
// -1: means we are visiting the colum by the up direction.
int[] y = {0, 1, 0, -1};
这种方向矩阵将会很常用在各种旋转数组上。。。。。。

class Solution{ //2ms
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new ArrayList<Integer>();
        int rows = matrix.length;
        int cols = matrix[0].length;  
        if (matrix == null || rows == 0 || cols == 0) {
            return res;   
        }          
        int visitedRows = 0;//已经遍历过的行
        int visitedCols = 0;
        int[] x = {1, 0, -1, 0};
        int[] y = {0, 1, 0, -1};
        // 0: right, 1: down, 2: left, 3: up.
        int direct = 0;  //方向矩阵的下标
        int startx = 0;//记录当前遍历到的横坐标
        int starty = 0;
        int candidateNum = 0;//记录需要遍历的行数或列数
        int step = 0;//记录当前行或列已经遍历过的个数
        while (true) {
            if (x[direct] == 0) {
                //遍历y轴方向.
                candidateNum = rows - visitedRows;
            } else {
                // 遍历x轴方向                                                                                                                                         candidateNum = cols - visitedCols;
            }
            if (candidateNum <= 0) {
                break;
            }
            res.add(matrix[startx][starty]);
            step ++;
            if (step == candidateNum) {
                step = 0;
                visitedRows += x[direct] == 0 ? 0: 1;
                visitedCols += y[direct] == 0 ? 0: 1;            
                // move forward the direction.
                direct ++;
                direct = direct % 4;
            }        
            // 根据方向来移动横坐标和纵坐标。
            startx += y[direct];
            starty += x[direct];
        }
        return res;
    }
}

转载于:https://my.oschina.net/liyurong/blog/1529392

旋转遍历矩阵 Spiral Matrix相关推荐

  1. LeetCode 螺旋矩阵(Spiral Matrix)

    思路:做四个方向的遍历右,下,左,上.重复循环这四个方向即得到螺旋矩阵. 注意问题: 1.边界 2.判断当前位置是否已经遍历(mark标志位) 3.vector为空或者只有一个元素 4.循环退出条件 ...

  2. python 遍历矩阵_Python3算法之十:矩阵旋转

    关注微信公众号"酸痛鱼",获得更多最新最全的文章. 本文中所涉及的代码,在未特殊声明的情况下,都是基于Python3程序设计语言编写的. 建议您在PC浏览器中阅读本文,以获得更好的 ...

  3. LeetCode 59 Spiral Matrix II(螺旋矩阵II)(Array)

    版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/5214 ...

  4. LeetCode Spiral Matrix II (生成螺旋矩阵)

     Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. F ...

  5. C#LeetCode刷题之#59-螺旋矩阵 II(Spiral Matrix II)

    目录 问题 示例 分析 问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/3678 访问. 给定一个正整数 n,生成一 ...

  6. C#LeetCode刷题之#54-螺旋矩阵(Spiral Matrix)

    问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/3672 访问. 给定一个包含 m x n 个元素的矩阵(m 行, ...

  7. css3transform rotate,CSS3详解:transform [旋转rotate、扭曲skew、缩放scale和移动translate以及矩阵变形matrix]...

    CSS3详解:transform [旋转rotate.扭曲skew.缩放scale和移动translate以及矩阵变形matrix] transform的属性包括:rotate() / skew() ...

  8. PAT1105:Spiral Matrix

    1105. Spiral Matrix (25) 时间限制 150 ms 内存限制 65536 kB 代码长度限制 16000 B 判题程序 Standard 作者 CHEN, Yue This ti ...

  9. LeetCode:Spiral Matrix I II

    Spiral Matrix Given a matrix of m x n elements (m rows, n columns), return all elements of the matri ...

最新文章

  1. python计算四元素组合算法_python – 算法,列表元素之间的最近点
  2. JQUERY打造隐藏在左侧的弹性弹出菜单
  3. python 求反函数_逆累积分布函数,累积分布函数及python实现
  4. 鸿合怎么删掉linux6_鸿合电子白板怎么校准?鸿合电子白板校准的方法
  5. python数据类型之元组类型
  6. 通过数据评估渠道用户质量的方法
  7. php用字母数字生成用户名,请问生成字母加数字
  8. [转载]c语言中命令行参数argc,argv
  9. div+css 兼容ie6 ie7 ie8 ie9和FireFox Chrome等浏览器方法
  10. mysql创建数据库sql语句_创建数据库的SQL语句:mysql数据库
  11. 微信表情包批量导出-2022年8月4日
  12. teraterm--一款超好用堪比MobaXterm的远程终端连接软件,能解决shell端tab键等自动补全命令功能的缺失问题
  13. win7系统如何恢复或重装IE8浏览器呢?
  14. 维基百科--文件系统大全
  15. 各大跨境电商卖家不容错过下半年的促销活动安排
  16. Echarts自定义数据视图(DataView)-按钮名称-刷新方法
  17. 1024程序员节来了,
  18. FPGA开源网站和论坛
  19. 编程方法论/架构设计/模式相关转载链接汇总
  20. 深度学习环境配置 和 CP-VTON 复现

热门文章

  1. 基于MATLAB和Python的频谱分析
  2. 考研结束了,使用SpringBoot开发一个考研管理系统
  3. springboot+vue在线音乐网站
  4. 勒索软件出新招,小心你的隐私和財产安全!
  5. textarea 固定大小,滚动条,限制拖动,文字对齐
  6. JQ-CSS-实现导航菜单效果
  7. 多线程端点服务发布程序(摘)
  8. 谈谈Visual Studio的缺点,比较Eclipse
  9. LR(0)语法制导翻译
  10. MATLAB报错:未定义函数或变量